![](/img/trans.png)
[英]How to deny access to the method if there is no value passed, or value is invalid?
[英]Consistent way to access route value parameters passed through querystring
我在global.asax中定義了以下路由
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Portal", action = "Index", id = UrlParameter.Optional }
);
我無法控制用戶是否使用“ / useraccount / edit / 1”或“ / useraccount / edit?id = 1”訪問頁面。 使用UrlHelper Action方法生成url時,如果id作為查詢字符串參數傳遞,則id值不包含在RouteData中。
new UrlHelper(helper.ViewContext.RequestContext).Action(
action, helper.ViewContext.RouteData.Values)
我正在尋找一種訪問id值的一致方法,無論使用哪個url訪問該頁面,還是一種自定義RouteData對象的初始化的方法,以便它檢查QueryString是否缺少路由參數,並在出現以下情況時添加它們他們被發現。
您可以使用
@Url.RouteUrl("Default", new { id = ViewContext.RouteData.Values["id"] != null ? ViewContext.RouteData.Values["id"] : Request.QueryString["id"] })
試試這個解決方案
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]));
}
擴展路線最終是滿足我需求的最簡單的解決方案; 感謝你的建議! 讓我知道我的解決方案是否存在任何明顯的問題(類名除外)。
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 }));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.