What is the difference between routes.MapMvcAttributeRoutes() and context.Routes.MapMvcAttributeRoutes();

12,773

This is an extension method, so that the object from which you call it is the first parameter. This parameter is a RouteCollection, and this collection is different in both cases:

  • In the first call are registered the routes of controllers "in the root" of the application which have routing attributes
  • In the second call the same is being done for controllers inside the current area

If you want to avoid the second call for each area, you can decorate your controllers with the [RouteArea("AreaName")] attribute.

If you want to have a better understanding of attribute routing, see this doc: Attribute Routing in ASP.NET MVC 5 Pay special attention to the Areas section.

Share:
12,773
Denis
Author by

Denis

Updated on June 04, 2022

Comments

  • Denis
    Denis almost 2 years

    I have mvc application with additional area named account

    I am using MvcSiteMapProvider for making breadcrumbs

    I have an action which returns details about specific invoice. This action's url is something like localhost/account/profile/invs-histr/details/ID, where ID is the id of invoice to display.

    I have accountAreaRegistration.cs for registering areas routes and I have RouteConfig.cs for registering global routes.

    Currently, I have to register route for localhost/account/profile/invs-histr/details/ID in both files. If I do not register this route in accountAreaRegistration.cs, I've got 404 exception. If I do not register this route in RouteConfig.cs, breadcrumbs are not being rendered.

    The begining of RouteConfig.cs file:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapMvcAttributeRoutes();
    }
    

    And accountAreaRegistration.cs:

    public override void RegisterArea(AreaRegistrationContext context)
    {
       context.Routes.MapMvcAttributeRoutes();
    }
    

    Can anyone explain me, what is the difference between routes.MapMvcAttributeRoutes() and context.Routes.MapMvcAttributeRoutes()?

    Why I should register the route in both files?

    Thank you in advance