Search code examples
asp.net-mvcasp.net-mvc-routingasp.net-mvc-areas

ASP.NET MVC the name of the area should not be a route


In my ASP.NET MVC project, I have areas that have a certain name like Admin but I'd like my route to use iAdmin.

For that I use the RegisterArea where I can specify my route, and it work well :

context.MapRoute(
            "Admin_default",
            "iAdmin/{action}",
            new { controller = "iAdmin", action = "Index" }
        );

However, in the project I have another routing that is the default one:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Identification", action = "Index" }
);

With this default routing that take the controller name, and because my controllers are named with the Area name and not the route name, (So AdminController instead of iAdminController) if the url is like /Admin, the routing will work, and I do not want that.

How can I prevent that?

I tried these two solutions :

  • I can ignore in each RegisterArea the route that I don't want, which seems okay but kind of too much because I'd have to ignore every action too I believe, unless I can use a RegEx
  • Or I can rename the controllers in my Areas to have the name I want, which honestly not only seems the simplest but also might be the correct answer if our original approach of naming controller was a bad idea / practice

My questions are :

  • Is there any other way to prevent the routing with the names of the controllers in our areas?
  • And is the original naming of our controller the problem ?

Thanks in advance for your time


Solution

  • This can be done in your controller by specifying alternate routing. For instance it sounds like you have a controller named iAdminController which responds to "/iAdmin/{action}" but you would like this to respond to "/Admin/{action}"

    [Route("Admin/[action]")]
    [Route("[controller]/[action]")]
    public class iAdminController
    {
        // ...
    }
    

    Edit: Alternatively if the controller was named AdminController and you also wanted the iAdmin route:

    [Route("iAdmin/[action]")]
    [Route("[controller]/[action]")]
    

    /Edit

    This configuration will continue to work with either iAdmin/ or Admin/ routes. (recommended, mainly to avoid breaking default {controller}/{action} routing rules) From my testing even though my URLs and redirects were going to the controller name (i.e. iAdmin in this case) with this routing the browser was showing the route as "Admin/", likely due to the order or the alternate routes.