views:

64

answers:

1

Due to factors outside my control, I need to handle urls like this:

I would like to route them to a specific controller/action with the val already parsed and bound (i.e. an argument to the action).

Ideally my action would look like this:

ActionResult BackwardCompatibleAction(int val)

I found this question: ASP.Net MVC routing legacy URLs passing querystring Ids to controller actions but the redirects are not acceptable.

I have tried routes that parse the query string portion but any route with a question mark is invalid.

I have been able to route the request with this:

routes.MapRoute(
    "dosomething.asp Backward compatibility",
    "{dosomething}.asp",
    new { controller = "MyController", action = "BackwardCompatibleAction"}
);

However, from there the only way to get to the value of val=? is via Request.QueryString. While I could parse the query string inside the controller it would make testing the action more difficult and I would prefer not to have that dependency.

I feel like there is something I can do with the routing, but I don't know what it is. Any help would be very appreciated.

+2  A: 

The parameter val within your BackwardCompatibleAction method should be automatically populated with the query string value. Routes are not meant to deal with query strings. The solution you listed in your question looks right to me. Have you tried it to see what happens?

This would also work for your route. Since you are specifying both the controller and the action, you don't need the curly brace parameter.

routes.MapRoute(
    "dosomething.asp Backward compatibility",
    "dosomething.asp",
    new { controller = "MyController", action = "BackwardCompatibleAction"}
);

If you need to parametrize the action name, then something like this should work:

routes.MapRoute(
    "dosomething.asp Backward compatibility",
    "{action}.asp",
    new { controller = "MyController" }
);

That would give you a more generic route that could match multiple different .asp page urls into Action methods.

http://www.bob.com/dosomething.asp?val=42 would route to MyController.dosomething(int val)

and http://www.bob.com/dosomethingelse.asp?val=42 would route to MyController.dosomethingelse(int val)

Dennis Palmer
Unbelievable. I tried it and it worked. Shouda just tried it. Thanks!!!
Jere.Jones