10

I'm working on a seemingly simple issue: in my Authorization filter I'm checking for a few things if one of the conditions is not met, I need to remove certain values from the Query string and redirect the user to the resulting URL. However, this is giving me a few more problems than I would like. It looks something like this:

public void OnAuthorization(AuthorizationContext filterContext)
{
    if (!SomeCondition()) {
        RedirectToCleanUrl(filterContext);
    }
}

In my RedirectToCleanUrl I'm stripping the query strings and attempt to redirect them to the new url. It looks like this:

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);
}

First off all, it doesn't work and even if it did, it's ugly. There must be a better way, right? What am I missing here?

1 Answer 1

8

Here's the code I ended up writing:

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);
    }
}

You might also want to UrlEncode the query string params, but I'll leave this up to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.