我正在处理一个看似简单的问题:在我的授权过滤器中,我检查一些条件是否满足条件,我需要从Query字符串中删除某些值,并将用户重定向到生成的URL.但是,这给了我一些比我想要的更多的问题.看起来像这样:
public void OnAuthorization(AuthorizationContext filterContext) { if (!SomeCondition()) { RedirectToCleanUrl(filterContext); } }
在我的RedirectToCleanUrl中,我剥离了查询字符串,并尝试将其重定向到新的URL.看起来像这样:
private void RedirectToCleanUrl(AuthorizationContext filterContext) { var queryStringParams = new NameValueCollection(filterContext.HttpContext.Request.QueryString); // Stripping the key queryStringParams.Remove("some_key"); var routeValueDictionary = new RouteValueDictionary(); foreach (string x in queryStringParams) { routeValueDictionary.Add(x,queryStringParams[x]); } foreach (var x in filterContext.RouteData.Values) { routeValueDictionary.Add(x.Key,x.Value); } filterContext.Result = new RedirectToRouteResult(routeValueDictionary); }
首先,它不起作用,即使是这样,它是丑陋的.一定要有更好的方法吧?我在这里缺少什么?
解决方法
这是我最后写的代码:
protected void StripQueryStringAndRedirect(System.Web.HttpContextBase httpContext,string[] keysToRemove) { var queryString = new NameValueCollection(httpContext.Request.QueryString); foreach (var key in keysToRemove) { queryString.Remove(key); } var newQueryString = ""; for (var i = 0; i < queryString.Count; i++) { if (i > 0) newQueryString += "&"; newQueryString += queryString.GetKey(i) + "=" + queryString[i]; } var newPath = httpContext.Request.Path + (!String.IsNullOrEmpty(newQueryString) ? "?" + newQueryString : String.Empty); if (httpContext.Request.Url.PathAndQuery != newPath) { httpContext.Response.Redirect(newPath,true); } }
您可能还想UrlEncode查询字符串params,但我会将其留给您.