用自定义routes把不同的querystring名对应到action同一个参数上
参考http://www.cnblogs.com/John-Connor/archive/2012/05/03/2478821.html
假设我们有一个action
public ActionResult Index(int uid)
在生成连接的地方,有两种不同的写法
1:
@Html.ActionLink("go", "index", new { id=1 })
2: @Html.ActionLink("go", "index", new { uid=1 })
有的传的是id,有的传的是uid。(为什么会这样我就不多说了,团队开发协调有问题)
现在是2正确,但是1不正确1生成的连接形式为 index/?id=1,希望这种也可以正确访问
继承RouteBase类,写一个自己的
1: public class UserIndexRoute:RouteBase
2: {
3: public override RouteData GetRouteData(HttpContextBase httpContext)
4: {
5: if (httpContext.Request.Url.AbsolutePath.ToLower() == "/user/index/")
6: {
7: if (!string.IsNullOrEmpty(httpContext.Request.QueryString["id"]))
8: {
9: var routes = new RouteData(this, new MvcRouteHandler());
10: routes.Values.Add("controller", "User");
11: routes.Values.Add("action", "Index");
12: routes.Values.Add("uid", httpContext.Request.QueryString["id"]);
13: return routes;
14: }
15: }
16: return null;
17: }
18:
19: public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
20: {
21: if (values.ContainsKey("controller") && values.ContainsKey("action") && values.ContainsKey("id") && values["controller"].ToString().ToLower() == "user" && values["action"].ToString().ToLower() == "index")
22: {
23: return new VirtualPathData(this, "User/Index/" + values["id"]);
24: }
25: return null;
26: }
27: }
在global里
1: routes.MapRoute(
2: "UserIndex",
3: "User/Index/{uid}",
4: new { controller = "User", action = "Index"}
5: );
6:
7: routes.Add("UserIndex_id", new UserIndexRoute());