Removing Specific Query String Parameters from a URL in C#

By FoxLearn 1/10/2025 2:54:40 AM   100
In web development, it's often necessary to manipulate URLs, such as removing specific query string parameters.

Below, we explore two different methods for removing query string parameters from a URL: one using a negative list (parameters to remove) and the other using a positive list (parameters to keep).

Removing Parameters Using a Negative List

This method allows you to specify the parameters you want to remove from the URL. Any parameters not included in the list will remain intact.

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

namespace MyApp
{
    public static class UrlExtension
    {
        public static string RemoveQueryStringsFromUrl(this string url, string[] keys)
        {
            // Ensure the URL contains a query string
            var uri = new Uri(url);
            var querystrings = HttpUtility.ParseQueryString(uri.Query);

            // Remove specified keys
            foreach (var key in keys)
            {
                querystrings.Remove(key);
            }

            // Rebuild the URL with the remaining query parameters
            var newQuery = querystrings.Count > 0 
                ? "?" + string.Join("&", querystrings.AllKeys.Select(k => $"{k}={querystrings[k]}"))
                : string.Empty;

            return uri.GetLeftPart(UriPartial.Path) + newQuery;
        }
    }
}

Usage

string url = "https://example.com/page/?id=1&p=2";
string urlWithoutP = url.RemoveQueryStringsFromUrl(new string[] { "p" });
string urlWithoutParams = url.RemoveQueryStringsFromUrl(new string[] { "p", "id" });

// Results:
// https://example.com/page/?id=1
// https://example.com/page

In the example above, the RemoveQueryStringsFromUrl method removes the p parameter from the URL, leaving only id=1. If both p and id are removed, the result is the URL without any query string.

Removing Parameters Using a Positive List

This method is slightly different it works by specifying which parameters should remain in the URL. All other parameters not included in the allowed list will be removed.

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

namespace MyApp
{
    public static class UrlExtension
    {
        public static string RemoveQueryStringsFromUrlWithPositiveList(this string url, string[] allowedKeys)
        {
            // Create a Uri instance to parse the URL
            var uri = new Uri(url);

            // Parse the query string
            var querystrings = HttpUtility.ParseQueryString(uri.Query);

            // Remove any keys that are not in the allowed list
            foreach (var key in querystrings.AllKeys.Except(allowedKeys))
            {
                querystrings.Remove(key);
            }

            // Rebuild the URL with the allowed query parameters
            var newQuery = querystrings.Count > 0 
                ? "?" + string.Join("&", querystrings.AllKeys.Select(k => $"{k}={querystrings[k]}"))
                : string.Empty;

            // Return the final URL with the remaining query parameters
            return uri.GetLeftPart(UriPartial.Path) + newQuery;
        }
    }
}

Usage

string url = "https://example.com/page/?id=1&p=2";
string urlWithOnlyId = url.RemoveQueryStringsFromUrlWithPositiveList(new string[] { "id" });
string urlWithOnlyP = url.RemoveQueryStringsFromUrlWithPositiveList(new string[] { "p" });

// Results:
// https://example.com/page/?id=1
// https://example.com/page/?p=2

Here, the RemoveQueryStringsFromUrlWithPositiveList method ensures that only the id parameter remains in the URL, and any other parameters, such as p, are removed. If you want to keep only the p parameter, you can pass new string[] { "p" } as the allowed keys.

These two methods provide a flexible and safe way to remove query string parameters from URLs in C#. You can either specify which parameters to remove (negative list) or which parameters to keep (positive list).