C# Remove specific Querystring parameters from URL

These 2 extension methods will remove specific query string parameters from an URL in a safe manner.

METHOD #1: SPECIFY THE PARAMETERS THAT SHOULD GO (NEGATIVE LIST):

using System;
using System.Linq;
using System.Web;

namespace MyCode
{
  public static class UrlExtension
  {
    public static string RemoveQueryStringsFromUrl(this string url, string[] keys)
    {
      if (!url.Contains("?"))
        return url;

      string[] urlParts = url.ToLower().Split('?');
      try
      {
        var querystrings = HttpUtility.ParseQueryString(urlParts[1]);
        foreach (string key in keys)
          querystrings.Remove(key.ToLower());

        if (querystrings.Count > 0)
          return urlParts[0] 
            + "?" 
            + string.Join("&", querystrings.AllKeys.Select(c => c.ToString() + "=" + querystrings[c.ToString()]));
        else
          return urlParts[0];
      }
      catch (NullReferenceException)
      {
        return urlParts[0];
      }
    }
  }
}

Usage/Test cases:

string url = "https://briancaos.wordpress.com/page/?id=1&p=2";
string url2 = url.RemoveQueryStringsFromUrl(url, new string[] {"p"});
string url3 = url.RemoveQueryStringsFromUrl(url, new string[] {"p", "id"});

//Result: 
// https://briancaos.wordpress.com/page/?id=1
// https://briancaos.wordpress.com/page

METHOD #2: SPECIFY THE PARAMETERS THAT MAY STAY (POSITIVE LIST):

using System;
using System.Linq;
using System.Web;

namespace MyCode
{
  public static class UrlExtension
  {
    public static string RemoveQueryStringsFromUrlWithPositiveList(this string url, string[] allowedKeys)
    {
      if (!url.Contains("?"))
        return url;

      string[] urlParts = url.ToLower().Split('?');
      try
      {
        var querystrings = HttpUtility.ParseQueryString(urlParts[1]);
        var keysToRemove = querystrings.AllKeys.Except(allowedKeys);

        foreach (string key in keysToRemove)
          querystrings.Remove(key);

        if (querystrings.Count > 0)
          return urlParts[0] 
		    + "?" 
			+ string.Join("&", querystrings.AllKeys.Select(c => c.ToString() + "=" + querystrings[c.ToString()]));
        else
          return urlParts[0];
      }
      catch (NullReferenceException)
      {
        return urlParts[0];
      }
    }
  }
}

Usage/Test cases:

string url = "https://briancaos.wordpress.com/page/?id=1&p=2";
string url2 = url.RemoveQueryStringsFromUrl(url, new string[] {"p"});
string url3 = url.RemoveQueryStringsFromUrl(url, new string[] {"p", "id"});

//Result: 
// https://briancaos.wordpress.com/page/?p=2
// https://briancaos.wordpress.com/page/?id=1&p=2

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , . Bookmark the permalink.

3 Responses to C# Remove specific Querystring parameters from URL

  1. Niels Sparenberg says:

    Hi Brian

    You can use the UriBuilder to do it a litle bit more smooth imo.
    Example:

    public static string RemoveQueryParameters(this string uriString, IEnumerable parametersToRemove)
    {
    try
    {
    var ub = new UriBuilder(uriString);
    var parsedQuery = HttpUtility.ParseQueryString(ub.Query);

    foreach (var p in parametersToRemove)
    parsedQuery.Remove(p);

    ub.Query = parsedQuery.ToString();
    return ub.ToString();
    }
    catch (UriFormatException) // if not a valid uri this is thrown from builder
    {
    return uriString;
    }
    }

    Like

  2. briancaos says:

    The UriBuilder is also a great solution. However, the UriBuilder will fail if the string provided is not an actual Url. Also, the ub.Query property will throw an exception, if the url provided is a relative url. My method is indeed more cumbersome, but also more forgiving.

    Like

  3. Joe556 says:

    Hi – I suggest you add “params” to the signature before string[] keys:
    public static string RemoveQueryStringsFromUrl(this string url, params string[] keys)

    Then you don’t have to have the cumbersome array declaration to remove / keep a single parameter…
    Old:
    string url2 = url.RemoveQueryStringsFromUrl(url, new string[] {“p”});
    string url3 = url.RemoveQueryStringsFromUrl(url, new string[] {“p”, “id”});

    New:
    string url2 = url.RemoveQueryStringsFromUrl(url, “p”);
    string url3 = url.RemoveQueryStringsFromUrl(url, “p”, “id”);

    (Note: this is still backwards compatible, so you can still pass an array if you want)

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.