Posted By

krisdb on 04/06/09


Tagged

c-sharp


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


ReplaceQueryParameterValue


 / Published in: C#
 

  1. Response.Redirect(ReplaceQueryParameterValue(Request.RawUrl, "all", "1"));
  2.  
  3. private string ReplaceQueryStringValue(string url, string key, string value)
  4. {
  5. return url.Contains(key) ? Regex.Replace(url, @"([?&]" + key + ")=[^?&]+", "$1=" + value) : (url + (url.Contains("?") ? "&" : "?") + key + "=" + value);
  6. }
  7.  
  8.  
  9. private string ReplaceQueryParameterValue(string query, string name, string value)
  10. {
  11. string output;
  12.  
  13. if (query.Contains(name + "="))
  14. {
  15. output = System.Text.RegularExpressions.Regex.Replace(query,
  16. @"(&|\?)" + name + @"=[0-9A-Za-z\+\!\*\(\)\'\-\$\,\.]+", @"$1" + name + "=" + value,
  17. System.Text.RegularExpressions.RegexOptions.IgnoreCase);
  18. }
  19. else
  20. output = query + (query.Contains("?") ? "&" : "?") + name + "=" + value;
  21.  
  22. return output;
  23. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: rogeskic on February 4, 2011

Hello, thanks for doing this! Howe can this be changed to support replacing a value that is encoded URL?? Any help would be appreciated.

Even if i replace it with an empty string (""), the result is that "HTTP" gets replaced, and the rest of the parameter value stays. coverimage=http%3A%2F%2Fgalleryserver....
coverimage=%3A%2F%2Fgalleryserver....

For example: If I start with this: "http://www.zazzle.com/api/create/at-238965785060790379?rf=238345325100453699&ax=DesignBlast&cg=196484196445896905&ed=true&br=true&rcg=196484196445896905&ds=true&continueUrl=http%3A%2F%2Fwww.zazzle.com%2Fmainepictures&rut=Go%20back%20to%20MainePictures's%20store&fwd=ProductPage&coverimage=http%3A%2F%2Fgalleryserver.greatmainepictures.com%2Fgs%2Fhandler%2Fgetmediaobject.ashx%3Fmoid%3D6%26dt%3D3%26g%3D0"

And want to replace the parameter "coverimage" with even just an empty String, ("") I get this as a result:

"http://www.zazzle.com/api/create/at-238965785060790379?rf=238345325100453699&ax=DesignBlast&cg=196484196445896905&ed=true&br=true&rcg=196484196445896905&ds=true&continueUrl=http%3A%2F%2Fwww.zazzle.com%2Fmainepictures&rut=Go%20back%20to%20MainePictures's%20store&fwd=ProductPage&coverimage=%3A%2F%2Fgalleryserver.greatmainepictures.com%2Fgs%2Fhandler%2Fgetmediaobject.ashx%3Fmoid%3D6%26dt%3D3%26g%3D0"

Posted By: krisdb on February 21, 2011

Did you try URLDecoding it?

You need to login to post a comment.