Davita
Davita

Reputation: 9124

Conditional routing in ASP.NET MVC

I'll try to describe my problem as simple as I can. I have several controllers which are loaded dynamically at runtime. Those controllers hosts several web apis for different partners. What I want to achieve is to have a prefix in URL before accessing the controller. In other words, I have Partner1 and Partner2. Both of them has some controllers, for example

Partner1: Service1Controller, Service2Controller2. Partner2: Api1Controller, Api2Controller etc.

Now I want to achieve the following. I want partner1's controllers to be accessible only with Partner1 prefix in the url, for example http://somehost.com/Partner1/Service1, but I don't want Api1Controller to be accessible from http://somehost.com/Partner1/Api1, but instead it should be accessible from http://somehost.com/Partner2/Api1.

Is there any way to achieve my goal?

Thanks

Upvotes: 1

Views: 1304

Answers (2)

Faust
Faust

Reputation: 15404

An inelegant solution could be to use 2 separate route mappings:

routes.MapRoute(
    "partner1", 
    "partner1/{controller}/{action}",
    new { contoller =  Service1Controller, action = "Index" },  
    new { contoller = @"(Service1Controller)|(Service2Controller)"}
);

routes.MapRoute(
    "partner2", 
    "partner2/{controller}/{action}",
    new { controller = Api1Controller, action = "Index" },   
    new { contoller = @"(Api1Controller)|(Api2Controller)"}
);  

Teh 4th parameter of MapRoute defines constraints as regular expressions

Upvotes: 1

Jeffrey Lott
Jeffrey Lott

Reputation: 7429

You could create a custom ActionFilter that looks at the Request and User and determines if the route is valid. If it's not, then you can return some ActionResult that either redirects or returns an error to the user.

Upvotes: 0

Related Questions