How to route legacy type urls in ASP.NET MVC

一曲冷凌霜 提交于 2019-12-08 08:08:20

问题


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

  • http://www.bob.com/dosomething.asp?val=42

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.


回答1:


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)



来源:https://stackoverflow.com/questions/1561766/how-to-route-legacy-type-urls-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!