2016-02-04 117 views
0

通过路径值的参数一致的方式如下路线访问通过查询字符串

routes.MapRoute(
    "Default", 
    "{controller}/{action}/{id}", 
    new { controller = "Portal", action = "Index", id = UrlParameter.Optional } 
); 

我无法控制用户是否有访问该页面“/ useraccount /编辑/ 1”或“/ useraccount /编辑?ID = 1”。当使用UrlHelper Action方法生成URL时,如果id作为查询字符串参数传递,则该值不包含在RouteData中。

new UrlHelper(helper.ViewContext.RequestContext).Action(
          action, helper.ViewContext.RouteData.Values) 

我正在寻找访问的id值,无论是用于访问网页,还是有办法自定义的RouteData对象的初始化该URL的一致的方式,以便它会检查查询字符串缺少路由参数并在找到它们时添加它们。

+0

它看起来像编写自定义路线可以让我通过覆盖GetRouteData添加缺少的值到的RouteData ;我会在测试完成后发布源代码。 – Failwyn

回答

0

扩展路由结束了我的需求最简单的方法;感谢你的建议!让我知道是否有任何明显的问题(除了课程名称)与我的解决方案。

FrameworkRoute.cs

public class FrameworkRoute: Route 
{ 
    public FrameworkRoute(string url, object defaults) : 
     base(url, new RouteValueDictionary(defaults), new MvcRouteHandler()) 
    { 
    } 

    public override RouteData GetRouteData(HttpContextBase httpContext) 
    { 
     var routeData = base.GetRouteData(httpContext); 
     if (routeData != null) 
     { 
      foreach (var item in routeData.Values.Where(rv => rv.Value == UrlParameter.Optional).ToList()) 
      { 
       var val = httpContext.Request.QueryString[item.Key]; 
       if (!string.IsNullOrWhiteSpace(val)) 
       { 
        routeData.Values[item.Key] = val; 
       } 
      } 
     } 

     return routeData; 
    } 
} 

的Global.asax.cs

protected override void Application_Start() 
{ 
     // register route 
     routes.Add(new FrameworkRoute("{controller}/{action}/{id}", new { controller = "Portal", action = "Index", id = UrlParameter.Optional })); 
1

您可以使用

@Url.RouteUrl("Default", new { id = ViewContext.RouteData.Values["id"] != null ? ViewContext.RouteData.Values["id"] : Request.QueryString["id"] }) 
0

尝试此解决方案

var qs = helper.ViewContext 
       .HttpContext.Request.QueryString 
       .ToPairs() 
       .Union(helper.ViewContext.RouteData.Values) 
       .ToDictionary(x => x.Key, x => x.Value); 

      var rvd = new RouteValueDictionary(qs); 

      return new UrlHelper(helper.ViewContext.RequestContext).Action(action, rvd); 

转换的NameValueCollection试试这个

public static IEnumerable<KeyValuePair<string, object>> ToPairs(this NameValueCollection collection) 
     { 
      if (collection == null) 
      { 
       throw new ArgumentNullException("collection"); 
      } 

      return collection.Cast<string>().Select(key => new KeyValuePair<string, object>(key, collection[key])); 
     }