基本上,我尝试使用MVC操作过滤器向所有浏览器请求中添加一些自定义查询参数。
我尝试添加动作过滤器并编写以下代码,但出现错误。 例如:NotSupportedException:集合的大小是固定的。
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
答案 0 :(得分:0)
最后通过重定向到动作过滤器获得了解决方案。
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);
}
}
}