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?
I wrote a helper for my razor project using some of the hints from other answers.
The ParseQueryString business is necessary because we are not allowed to tamper with the QueryString object of the current request.
I use it like this:
If you want it to take more than one value, just change the parameters to a Dictionary and add the pairs to the query string.
I added the following method to my PageBase class.
To call:
I answered a similar question a while ago. Basically, the best way would be to use the class
HttpValueCollection
, which ASP.NET'sRequest.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
extendsNameValueCollection
, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides aToString()
method to later rebuild the query string from the underlying collection.Example:
Combined the top answers to create an anonymous object version:
That generates this:
Here's the code:
How about creating extension methods that allow you to add the parameters in a fluent style like this?
Here's the overload that uses a
string
:And here's the overload that uses a
StringBuilder
:Just wanted to throw in my 2 cents:
The docs say that
uri.Query
will start with a?
if it's non-empty and you should trim it off if you're going to modify it.Note that
HttpUtility.UrlEncode
is found inSystem.Web
.Usage: