Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a value from querystring in MVC3 and redirect to the resulting URL

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?

like image 578
MK_Dev Avatar asked Feb 08 '12 03:02

MK_Dev


1 Answers

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.

like image 133
MK_Dev Avatar answered Sep 28 '22 08:09

MK_Dev