2

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 ?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm going to test tonight it but it seems like a viable solution
I would add that, to make it work, you need to put the admin routes section before the default one
1

Try removing with this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.