queen3
queen3

Reputation: 15501

ASP.NET MVC dynamic route that is same as default controller/action

I need routes to match sometimes controllers, and sometimes - database values. Here's an example:

/controller/action?id=test - this is the default {controller}/{action} route

/name/type?flag=test - this is my custom {dbvalue}/{dbvalue} route

As you can see, the two routes are the same. But if {controller} or {action} is a specific value (only known at runtime because it depends on DB) - I need the route to match my other route (i.e. /specificcontroller/handleall(string name, string type) action).

Is it possible?

Upvotes: 0

Views: 1340

Answers (2)

CallMeLaNN
CallMeLaNN

Reputation: 8558

This is not tested yet but just an idea:

Global.asax:

routes.MapRoute("DbRoute", "{dbValue1}/{dbValue2}", new {controller = "RouteController", action = "Index"});
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional});

then in method action Index() inside class RouteController, you check for the dbValue1 and dbValue2. If not match, you can use RedirectToRoute("Default", ...) method.

By this way, any request will match DbRoute first and RouteController will check for the db value, if not match simply forward the route to the Default and render the view based on controller/action.

Upvotes: 0

queen3
queen3

Reputation: 15501

OK, the answer would be to implement IRouteConstraint to exclude DB values from the {controller} values accepted in the default route.

E.g.

 routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },  // Parameter defaults
            new { controller = new ExcludeValuesConstraint("dbvalue1", "dbvalue2") }
        );

Of course excluded values have to be dynamic.

The trick was not to add constraints to my route, but to exclude the values from the default route.

Upvotes: 1

Related Questions