A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are some nifty details you need to take care of like, appending an &
if not the first parameter, encoding the parameters etc.
The code to do it is very simple, but a bit tedious:
StringBuilder SB = new StringBuilder();
if (NeedsToAddParameter A)
{
SB.Append("A="); SB.Append(HttpUtility.UrlEncode("TheValueOfA"));
}
if (NeedsToAddParameter B)
{
if (SB.Length>0) SB.Append("&");
SB.Append("B="); SB.Append(HttpUtility.UrlEncode("TheValueOfB")); }
}
This is such a common task one would expect a utility class to exist that makes it more elegant and readable. Scanning MSDN, I failed to find one—which brings me to the following question:
What is the most elegant clean way you know of doing the above?
This is another (maybe redundant :-]) way for do that.
The conceptuals are the same of the Vedran answer in this page (take a look here).
But this class is more efficient, because it iterate through all Keys only one time: when
ToString
is invoked.The formatting code is also semplified and improved.
Hope that could be helpful.
If you look under the hood the QueryString property is a NameValueCollection. When I've done similar things I've usually been interested in serialising AND deserialising so my suggestion is to build a NameValueCollection up and then pass to:
Possibly I could've formatted that better :)
I imagine there's a super elegant way to do this in LINQ too...
Flurl [disclosure: I'm the author] supports building query strings via anonymous objects (among other ways):
The optional Flurl.Http companion lib allows you to do HTTP calls right off the same fluent call chain, extending it into a full-blown REST client:
The full package is available on NuGet:
PM> Install-Package Flurl.Http
or just the stand-alone URL builder:
PM> Install-Package Flurl
[Also late entry]
Chain-able wrapper class for HttpValueCollection:
Example usage:
My offering:
Usage:
A quick extension method based version:
You could use a where clause to select which parameters get added to the string.