2012-02-08 25 views
10

我正在處理一個看似簡單的問題:在我的授權過濾器中,如果其中一個條件未滿足,我將檢查幾件事情,從查詢字符串中刪除某些值並將用戶重定向到生成的URL。但是,這給我帶來了比我想要的更多的問題。它看起來是這樣的:從MVC3中的查詢字符串中刪除一個值並重定向到生成的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); 
} 

首先,它不起作用,即使它做到了,它也很難看。必須有更好的方式,對吧?我在這裏錯過了什麼?

回答

7

下面的代碼我最後寫:

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查詢字符串參數,可以但我會離開這個給你。

相關問題