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 so
Combined the top answers to create an anonymous object version:
var queryString = HttpUtility2.BuildQueryString(new
{
key2 = "value2",
key1 = "value1",
});
That generates this:
key2=value2&key1=value1
Here's the code:
public static class HttpUtility2
{
public static string BuildQueryString(T obj)
{
var queryString = HttpUtility.ParseQueryString(string.Empty);
foreach (var property in TypeDescriptor.GetProperties(typeof(T)).Cast())
{
var value = (property.GetValue(obj) ?? "").ToString();
queryString.Add(property.Name, value);
}
return queryString.ToString();
}
}