Arif YILMAZ Arif YILMAZ - 21 days ago 5
C# Question

Controller's URL in Area is too long, how to shorten URL?

I am new to Area term in MVC and I want to use it. I have the following directories that points to the controller in Area.

Areas > Admin > Controllers > AdminController


When I want to visit the Index Action of AdminController, I need to visit http://localhost/Admin/Admin. I want to get rid of the second "Admin". I want to type http://localhost/Admin/ only. How can I do that?

AdminAreaRegistration.cs has the following MapRoute

public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}

Answer

You have not specified a default value for the controller so unless you include it in the url, the routing engine has no way it identify which controller you want to navigate to. You can solve this by giving a default value for the controller name

context.MapRoute(
    "Admin_default",
    "Admin/{controller}/{action}/{id}",
    new { controller = "Admin", action = "Index", id = UrlParameter.Optional }
);

While that means that ../Admin will navigate to the Index() method of AdminController, it still means that if you want to navigate to another method in AdminController, your url will need to be ../Admin/Admin/AnotherMethod which is probably not what you want.

The purpose of areas is to logically group your controllers and methods. For example a shopping cart app might have a ProductsController where users might navigate to ../Product to display a list of products or ../Product/Details/1 to display details of a product. But the app might need other methods for suppliers to create and edit their products so you would create a separate Suppliers area where ../Suppliers/Products would navigate to their list of products, and ../Suppliers/Products/Edit/1 would allow them to update details of their product.

Having a AdminController in a Admin area does not really make sense, and I suggest that it should be HomeController if it contains general methods associated with admin tasks (and the route definition would then be new { controller = "Home", .. }