Reputation: 1874
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.
E.g.
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 ?
Upvotes: 2
Views: 5489
Reputation: 34992
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.
Upvotes: 3
Reputation: 2343
Try removing with this
RouteTable.Routes.Remove(RouteTable.Routes["NAME ROUTE YOU WISH TO RMOVE"]);
Upvotes: 1