Url structure

I need to create a url with a query string in C #. What is the best approach to this? Right now, I'm using something like:

string url = String.Format("foo.aspx?{0}={1}&{2}={3}", "a", 123, "b", 456); 

Is there a better, preferred approach?

+4
source share
3 answers

I think this is a good method if it always knows what parameters you have, if it is unknown at a time when you can always save the list <KeyValuePair <string, string β†’> with the key being the name and value being the value , then build the query string using a foreach loop like

 StringBuilder sb = new StringBuilder(); foreach(KeyValuePair<string,string> q in theList) { // build the query string here. sb.Append(string.format("{0}={1}&", q.Key, q.Value); } 

Note: the code has not been verified and has not been compiled, so it may not work as it is.

+5
source

I think you should use Server.UrlEncode for each of the arguments so that you don't send any bad characters to the URL.

+5
source

I wrote a neat little open source library for this kind of thing. Check out WebBuddy and in particular UriBuddy . The binaries are for Silverlight, but you can easily browse the source and rip everything you need.

Here is what you would call UriBuddy:

 // Take a base url Uri sample = new Uri("http://www.nytimes.com"); // some highly useful parameters Dictionary<String, String> query = new Dictionary<string, string> { {"param1","nice"}, {"param2","code man"} }; // create a new url using a chained style of coding Uri newSample = sample .AppendPath("/pages/world") .AppendQueryValues(query); 

By the way, I never had to do such things outside of Silverlight. I am sure that the β€œreal” .NET library has built-in functions that are very similar to mine.

+1
source

All Articles