Barbaros Alp
Barbaros Alp

Reputation: 6434

How can I remove item from querystring in asp.net using c#?

I want remove "Language" querystring from my url. How can I do this? (using Asp.net 3.5 , c#)

Default.aspx?Agent=10&Language=2

I want to remove "Language=2", but language would be the first,middle or last. So I will have this

Default.aspx?Agent=20

Upvotes: 54

Views: 121431

Answers (16)

Sunny
Sunny

Reputation: 119

ASP .NET Core (native, don't have to reference any additional libraries)

Within an ASP .NET Core Controller you would have access to an instance of Request

  • Request.Query is a query collection representing the query parameters, cast it to a list

  • From which you can filter and remove the params you want

  • Use QueryString.Create, which can take the list you just filtered as an input & generate a query string directly

     var removeTheseParams = new List<string> {"removeMe1", "removeMe2"}.AsReadOnly();
    
     var filteredQueryParams = Request.Query.ToList().Where(filterKvp => !removeTheseParams.Contains(filterKvp.Key));
     var filteredQueryString = QueryString.Create(queryParamsFilteredList).ToString();
    
     //Example: Console.Writeline(filteredQueryString) will give you "?q1=v1&q2=v2"
    

Optional Part Below: Can also encode those values if they are unsafe, so in addition to the Where() above UrlEncode the query parameter keys and values using a Select() as shown below:

     //Optional
     .Select(cleanKvp => new KeyValuePair<string, string?>(UrlEncoder.Default.Encode(cleanKvp.Key),UrlEncoder.Default.Encode(cleanKvp.Value)))

Upvotes: 0

Kurkula
Kurkula

Reputation: 6762

Parse Querystring into a NameValueCollection. Remove an item. And use the toString to convert it back to a querystring.

using System.Collections.Specialized;

NameValueCollection filteredQueryString = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
filteredQueryString.Remove("appKey");

var queryString = '?'+ filteredQueryString.ToString();

Upvotes: 0

yajiv
yajiv

Reputation: 2941

string queryString = "Default.aspx?Agent=10&Language=2"; //Request.QueryString.ToString();
string parameterToRemove="Language";   //parameter which we want to remove
string regex=string.Format("(&{0}=[^&\s]+|{0}=[^&\s]+&?)",parameterToRemove);
string finalQS = Regex.Replace(queryString, regex, "");

https://regexr.com/3i9vj

Upvotes: 0

Blairg23
Blairg23

Reputation: 12075

  1. Gather your query string by using HttpContext.Request.QueryString. It defaults as a NameValueCollection type.
  2. Cast it as a string and use System.Web.HttpUtility.ParseQueryString() to parse the query string (which returns a NameValueCollection again).
  3. You can then use the Remove() function to remove the specific parameter (using the key to reference that parameter to remove).
  4. Use case the query parameters back to a string and use string.Join() to format the query string as something readable by your URL as valid query parameters.

See below for a working example, where param_to_remove is the parameter you want to remove.

Let's say your query parameters are param1=1&param_to_remove=stuff&param2=2. Run the following lines:

var queryParams = System.Web.HttpUtility.ParseQueryString(HttpContext.Request.QueryString.ToString());
queryParams.Remove("param_to_remove");
string queryString = string.Join("&", queryParams.Cast<string>().Select(e => e + "=" + queryParams[e]));

Now your query string should be param1=1&param2=2.

Upvotes: 2

Segev Dagan
Segev Dagan

Reputation: 119

well I have a simple solution , but there is a little javascript involve.

assuming the Query String is "ok=1"

    string url = Request.Url.AbsoluteUri.Replace("&ok=1", "");
   url = Request.Url.AbsoluteUri.Replace("?ok=1", "");
  Response.Write("<script>window.location = '"+url+"';</script>");

Upvotes: 0

Paulius Zaliaduonis
Paulius Zaliaduonis

Reputation: 5189

Here is a simple way. Reflector is not needed.

    public static string GetQueryStringWithOutParameter(string parameter)
    {
        var nameValueCollection = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
        nameValueCollection.Remove(parameter);
        string url = HttpContext.Current.Request.Path + "?" + nameValueCollection;

        return url;
    }

Here QueryString.ToString() is required because Request.QueryString collection is read only.

Upvotes: 46

Vishal Nayan
Vishal Nayan

Reputation: 85

Try this ...

PropertyInfo isreadonly   =typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);    

isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Remove("foo");

Upvotes: 3

Pedro Geada
Pedro Geada

Reputation: 19

If you have already the Query String as a string, you can also use simple string manipulation:

int pos = queryString.ToLower().IndexOf("parameter=");
if (pos >= 0)
{
    int pos_end = queryString.IndexOf("&", pos);
    if (pos_end >= 0)   // there are additional parameters after this one
        queryString = queryString.Substring(0, pos) + queryString.Substring(pos_end + 1);
    else
        if (pos == 0) // this one is the only parameter
            queryString = "";
        else        // this one is the last parameter
            queryString=queryString.Substring(0, pos - 1);
}

Upvotes: 0

Pita.O
Pita.O

Reputation: 1837

Get the querystring collection, parse it into a (name=value pair) string, excluding the one you want to REMOVE, and name it newQueryString

Then call Response.Redirect(known_path?newqueryString);

Upvotes: 1

annakata
annakata

Reputation: 75872

My personal preference here is rewriting the query or working with a namevaluecollection at a lower point, but there are times where the business logic makes neither of those very helpful and sometimes reflection really is what you need. In those circumstances you can just turn off the readonly flag for a moment like so:

// reflect to readonly property
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

// make collection editable
isreadonly.SetValue(this.Request.QueryString, false, null);

// remove
this.Request.QueryString.Remove("foo");

// modify
this.Request.QueryString.Set("bar", "123");

// make collection readonly again
isreadonly.SetValue(this.Request.QueryString, true, null);

Upvotes: 26

Barbaros Alp
Barbaros Alp

Reputation: 6434

Finally,

hmemcpy answer was totally for me and thanks to other friends who answered.

I grab the HttpValueCollection using Reflector and wrote the following code

        var hebe = new HttpValueCollection();
        hebe.Add(HttpUtility.ParseQueryString(Request.Url.Query));

        if (!string.IsNullOrEmpty(hebe["Language"]))
            hebe.Remove("Language");

        Response.Redirect(Request.Url.AbsolutePath + "?" + hebe );

Upvotes: 37

Igal Tabachnik
Igal Tabachnik

Reputation: 31548

I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection, which the QueryString property actually is, unfortunately it is internal in the .NET framework. You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.

HttpValueCollection extends NameValueCollection, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString() method to later rebuild the query string from the underlying collection.

Upvotes: 10

xcud
xcud

Reputation: 14732

If it's the HttpRequest.QueryString then you can copy the collection into a writable collection and have your way with it.

NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("Language");

Upvotes: 116

Jason Kester
Jason Kester

Reputation: 6031

You don't make it clear whether you're trying to modify the Querystring in place in the Request object. Since that property is read-only, I guess we'll assume you just want to mess with the string.

... In which case, it's borderline trivial.

  • grab the querystring off the Request
  • .split() it on '&'
  • put it back together into a new string, while sniffing for and tossing out anything starting with "language"

Upvotes: 1

David Morton
David Morton

Reputation: 16505

Yes, there are no classes built into .NET to edit query strings. You'll have to either use Regex or some other method of altering the string itself.

Upvotes: 0

RKitson
RKitson

Reputation: 2013

You're probably going to want use a Regular Expression to find the parameter you want to remove from the querystring, then remove it and redirect the browser to the same file with your new querystring.

Upvotes: 0

Related Questions