Created
March 19, 2014 14:03
-
-
Save sandcastle/9642282 to your computer and use it in GitHub Desktop.
Simple query string builder for clients.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class QueryStringBuilder : NameValueCollection | |
{ | |
public QueryStringBuilder() | |
: base(StringComparer.InvariantCultureIgnoreCase) { } | |
public QueryStringBuilder(NameValueCollection collection) | |
: base(StringComparer.InvariantCultureIgnoreCase) | |
{ | |
Add(collection); | |
} | |
public QueryStringBuilder(object items) | |
: base(StringComparer.InvariantCultureIgnoreCase) | |
{ | |
if (items != null) | |
{ | |
foreach (var propertyInfo in items.GetType().GetProperties()) | |
{ | |
base.Add( | |
propertyInfo.Name, | |
(propertyInfo.GetValue(items, null) ?? "").ToString()); | |
} | |
} | |
} | |
public override string ToString() | |
{ | |
var builder = new StringBuilder(); | |
var first = true; | |
foreach (var item in AllKeys) | |
{ | |
builder.AppendFormat("{0}{1}={2}", | |
first ? "?" : "&", | |
Uri.EscapeUriString(item), | |
Uri.EscapeUriString(this[item])); | |
first = false; | |
} | |
return builder.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment