[英]Add custom parameter into every query string using MVC action filter
基本上我嘗試使用MVC動作過濾器將一些自定義查詢參數添加到我的所有瀏覽器請求中。
我嘗試添加動作過濾器並寫下面的代碼,但收到錯誤。 like:NotSupportedException:Collection具有固定大小。
public class CustomActionFilters : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.RouteData.Values.Keys.Add("customPara");
filterContext.RouteData.Values.Values.Add("myAllcustomparamter");
//OR
filterContext.HttpContext.Request.Query.Keys.Add("customPara=myAllcustomparamter");
}
}
所以,如果我寫入url: http:// localhost:15556 /
它將是http:// localhost:15556?customPara = myAllcustomparamter
如果打開任何其他頁面,如http:// localhost:15556 / image ,它將是http:// localhost:15556 / image?customPara = myAllcustomparamter或http:// localhost:15556 / image?inbuildparamter = anyvalue它將是http ://本地主機:15556 /圖像inbuildparamter = anyvalue&customPara = myAllcustomparamter
最后通過重定向到動作過濾器獲得解決方案。
public class CustomActionFilters : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string longurl = HttpContext.Current.Request.Url.AbsoluteUri;
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
var myAllcustomparamter = "myAllcustomparamterhere";
query.Add("customPara", myAllcustomparamter);
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
if (!filterContext.HttpContext.Request.QueryString.HasValue || (filterContext.HttpContext.Request.QueryString.HasValue && !filterContext.HttpContext.Request.QueryString.Value.Contains("customPara")))
{
filterContext.Result = new RedirectResult(longurl);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.