简体   繁体   中英

How to disable default route on controller ASP.NET MVC 5

I'm building a web application (ASP.NET MVC 5) with a custom admin section where all the parameters of the apps are.

I want to be able to easily change the name of this section.

Eg

myapp.com/admin/{controller}/{action}

could be

myapp.com/custom-admin-name/{controller}/{action}

I've tried to use areas but it seems like it would be hard to edit their name since all the controllers and models are bound to the area's namespace .

I've also tried to set custom routes

routes.MapRoute(
    "AdminControllerAction",
    "custom-admin-name/{controller}/{action}",
    new { controller = "Dashboard", action = "Index" }
);

So I could do

mywebsite.com/custom-admin-name/dashboard/index

But the problem with that is that my admin controllers and actions are still callable using

mywebsite.com/dashboard/index

Is it possible to cancel the default routing of a controller/action ?

Is there any more viable solutions to this problem that I wouldn't have thought about ?

There is a way to restrict the controller namespaces for a given route, so controllers which don't belong to those namespaces will be ignored.

For example, the following will be restricted to controllers in the namespace YourApp.Controllers (You can add multiple namespaces if needed):

Route route = routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "YourApp.Controllers" }                
);
route.DataTokens["UseNamespaceFallback"] = false;

Disabling the namespace fallback is important, otherwise you will just be prioritizing those namespaces.

So, you could restrict the default route to the namespace YourApp.Controllers as above and create a custom admin route restricted to the namespace YourApp.Controllers.Admin :

Route route = routes.MapRoute(
    "AdminControllerAction",
    "custom-admin-name/{controller}/{action}",
    new { controller = "Dashboard", action = "Index" },
    namespaces: new[] { "YourApp.Controllers.Admin" }                
);
route.DataTokens["UseNamespaceFallback"] = false;

Please note that as mentioned by Tareck, the admin route has to be defined before the general route.

尝试与此删除

RouteTable.Routes.Remove(RouteTable.Routes["NAME ROUTE YOU WISH TO RMOVE"]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM