Search code examples
asp.net-coreasp.net-core-mvcattributerouting

Registering routes with ASP.Net 5's MVC 6 Attribute Routing


When using Attribute Routing in ASP.Net MVC 5 you would call the command routes.MapMvcAttributeRoutes(); and then just add the Route() tag to the Controller/Actions you wanted to build routes to. I am now trying to do this in ASP.Net MVC 6 and have found many pages that show you how to do it, which is really no different than in MVC 5, but they don't show you where or how to register those routes.

Does ASP.Net MVC 6 just due it for you automatically or is there an equivalent to routes.MapMvcAttributeRoutes(); that I have to call some where?


Solution

  • If you have enabled MVC in your Startup class using app.UseMvc(), then you already have support for routing via the RouteAttribute.

    You can just add the RouteAttribute to a method of one of your controllers, e.g.:

    [Route("/example")]
    public IActionResult Example()
    {
        // …
    }
    

    That makes the route available under /example instead of the default /ControllerName/Example.

    You can also use the RouteAttribute on the controller class, e.g.

    [Route("test/[action]")]
    public class ExampleController : Controller
    {
        // …
    }
    

    So actions would be available under /test/MethodName instead of Example/MethodName.