1



In my Asp.NET MVC4 web project, I have many controllers and I want to put them into subdirectories under the folder "Controllers". Some controllers will have the same name due to their major jobs, but they will be put under different subdirectories, which means different namespaces. I want to do a url routing for those controllers. How can I make the routing consider the namespaces that the controllers with the same name exist? Could you show some code how to do that in Global.asax file?
Thanks a lot.

2 Answers 2

6

You need several MapRoute-s - at lease one for each namespace.

 // match all controllers in first namespace
 routes.MapRoute(
    name: "Namespace1Routes",
    url: "path1/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "My.Namespace1" }
 );

 // match all controllers in second and third namespaces
 routes.MapRoute(
    name: "Namespace2Routes",
    url: "path2/{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new[] { "My.Namespace2", "My.Namespace3" }
 );
Sign up to request clarification or add additional context in comments.

2 Comments

So for each controller that has the same name in different namespaces, would you need a route for each controller then?
No, you need one route for each path+namespace(s) pair, no matter how many controllers are in this namespace(s).
1
routes.MapRoute(
"Home",
"Index/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new string[] { "Project.Controllers" }

);

Project.Controllers -is namespace

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.