Last active
December 20, 2016 01:25
-
-
Save deepumi/d6634e38b98e4552ca4dda19bbff0359 to your computer and use it in GitHub Desktop.
Build query string using URIBuilder
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 UriQueryStringBuilder : UriBuilder | |
{ | |
private readonly IDictionary<string, string> _queryParameters; | |
public UriQueryStringBuilder(string schemeName, string hostName, string path) : this(schemeName, hostName, path, null) { } | |
public UriQueryStringBuilder(string schemeName, string hostName, string path, IEnumerable<KeyValuePair<string, string>> queryParameters) : this(schemeName, hostName,path,null) | |
{ | |
if (queryParameters == null) return; | |
foreach (KeyValuePair<string,string> item in queryParameters) | |
{ | |
AddQueryParameter(item.Key, item.Value); | |
} | |
} | |
public UriQueryStringBuilder(string schemeName, string hostName, string path, IDictionary<string, string> queryParameters) : base(schemeName, hostName) | |
{ | |
_queryParameters = queryParameters ?? new Dictionary<string,string>(); | |
Path = path; | |
} | |
public IDictionary<string, string> QueryParameters => _queryParameters; | |
public void AddQueryParameter(string key, string value) | |
{ | |
if (key == null) throw new ArgumentNullException(nameof(key)); | |
if (_queryParameters.ContainsKey(key)) throw new ArgumentException("An element with the same key already exists",nameof(key)); | |
_queryParameters.Add(key, value ?? string.Empty); | |
} | |
public override string ToString() | |
{ | |
var query = new StringBuilder(); | |
foreach (var item in _queryParameters.Keys) | |
{ | |
query.Append($"{item}={Uri.EscapeUriString(_queryParameters[item])}&"); | |
} | |
if (query.Length > 0) | |
{ | |
query.Length--; //Trim last character '&' | |
Query = query.ToString(); | |
} | |
return base.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment