Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse function of HttpUtility.ParseQueryString

.Net's System.Web.HttpUtility class defines the following function to parse a query string into a NameValueCollection:

public static NameValueCollection ParseQueryString(string query);

Is there any function to do the reverse (i.e. to convert a NameValueCollection into a query string)?

like image 202
Palani Avatar asked Apr 09 '10 05:04

Palani


3 Answers

I found that a combination of UriBuilder and HttpUtility classes meets my requirements to manipulate query parameters. The Uri class on its own is not enough, particularly as its Query property is read only.

var uriBuilder = new UriBuilder("http://example.com/something?param1=whatever");
var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
queryParameters.Add("param2", "whatever2");
queryParameters.Add("param3", "whatever2");
uriBuilder.Query = queryParameters.ToString();
var urlString = uriBuilder.Uri.ToString();

The above code results in the URL string: http://example.com/something?param1=whatever&param2=whatever2&param3=whatever2

Note that the ToString() goes via a Uri property, otherwise the output string would have an explicit port 80 in it.

It's nice to be able to do all this using framework classes and not have to write our own code.

like image 69
NickBeaugié Avatar answered Oct 05 '22 11:10

NickBeaugié


System.Collections.Specialized.NameValueCollection does NOT support this, but a derived internal class System.Web.HttpValueCollection DOES (by overriding ToString()).

Unfortunately (being internal) you cannot instantiate this class directly, but one is returned by HttpUtility.ParseQueryString() (and you can call this with String.Empty, but not Null).

Once you have a HttpValueCollection, you can fill it from your original NameValueCollection by calling Add(), before finally calling ToString().

var nameValueCollection = new NameValueCollection {{"a","b"},{"c","d"}};
var httpValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
var qs = httpValueCollection.ToString();

nameValueCollection.ToString() = "System.Collections.Specialized.NameValueCollection" httpValueCollection.ToString() = "a=b&c=d"

like image 25
Ivan Hamilton Avatar answered Oct 21 '22 04:10

Ivan Hamilton


A NameValueCollection has an automatic ToString() method that will write all your elements out as a querystring automatically.

you don't need to write your own.

var querystringCollection = HttpUtility.ParseQueryString("test=value1&test=value2");

var output = querystringCollection.ToString(); 

output = "test=value1&test=value2"

like image 4
Doug Avatar answered Oct 21 '22 06:10

Doug