2017-08-21 1 views
0

So habe ich eine HomeController, um darauf zugreifen zusammen mit Actions Ich muss url.com/home/action eingeben.Change Controller Route in ASP.NET Core

Wäre es möglich, dies zu etwas anderem wie url.com/anothernamethatpointstohomeactual/action?

Antwort

1

Mit dem Attribut Route oben auf Ihrem Controller können Sie die Route auf dem gesamten Controller definieren. [Route("anothernamethatpointstohomeactually")]

Sie können mehr lesen here.

1

Sie können neue Routes in Ihrem Startup.Configure Methode in Ihrem app.UseMvc(routes => Block hinzu:

routes.MapRoute(
       name: "SomeDescriptiveName",      
       template: "AnotherNameThatPointsToHome/{action=Index}/{id?}", 
       defaults: new { controller = "Home"} 
      ); 

Der Code ist ganz ähnlich wie ASP.NET MVC.

Weitere Informationen finden Sie unter Routing in ASP.NET Core.

Unten finden Sie für ASP.NET MVC (nicht ASP.NET MVC-Core)

Sie können auch einen neuen Route über routes.MapRoute in Ihrem RouteConfig hinzufügen:

routes.MapRoute(
      name: "SomeDescriptiveName", 
      url: "AnotherNameThatPointsToHome/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

Stellen Sie sicher, Sie einfügen der Code, bevor Sie Ihre Route Default definieren.

Weitere Informationen finden Sie unter docs.

5

Ich empfehle Ihnen, Attribut-Routing zu verwenden, aber natürlich hängt es von Ihrem Szenario ab.

[Route("prefix")] 
public class Home : Controller { 

    [HttpGet("name")] 
    public IActionResult Index() { 
    } 

} 

Dies wird bei url.com/prefix/name

finden viele Optionen Es gibt Routing-Attribut, einige Beispiele:

[Route("[controller]")] // there are placeholders for common patterns 
          as [area], [controller], [action], etc. 

[HttpGet("")] // empty is valid. url.com/prefix 

[Route("")] // empty is valid. url.com/name 

[HttpGet("/otherprefix/name")] // starting with/won't use the route prefix 

[HttpGet("name/{id}")] 
public IActionResult Index(int id){ ... // id will bind from route param. 

[HttpGet("{id:int:required}")] // you can add some simple matching rules too. 

prüfen Attribute Routing official docs

Verwandte Themen