基本上我尝试使用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://localhost:15556/image?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);
}
}
}