用自定义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());
这样,当访问index/?id=1时,自动转向了index/?uid=1。而在生成连接时把new{id=1}的,也生成为了/index/1的形式。
posted @ 2012-08-22 13:34  czcz1024  阅读(187)  评论(0编辑  收藏  举报