0

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?

2 Answers 2

1

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.

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

Comments

0

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.

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.