c# - Building URI with the http client API -
i have build uri address dynamic query strings , looking comfortable way build them via code.
i browsed system.net.http assembly doesn't found class or method case. api not provide this? search results here @ stackoverflow uses httputility class system.web, don't want reference asp.net components in class library.
i need uri : http://www.mybase.com/get?a=1&b=c.
thanks in advance helping!
update (2013/9/8):
my solution create uri builder uses system.net.webutilitiy class encoding values (the imported nuget package unfortunately didn't provide strong name key). here's code :
/// <summary> /// helper class creating uri query string parameter. /// </summary> internal class urlbuilder { private stringbuilder urlstringbuilder { get; set; } private bool firstparameter { get; set; } /// <summary> /// creates instance of uribuilder /// </summary> /// <param name="baseurl">the base address (e.g: http://localhost:12345)</param> public urlbuilder(string baseurl) { urlstringbuilder = new stringbuilder(baseurl); firstparameter = true; } /// <summary> /// adds new parameter uri /// </summary> /// <param name="key">the key </param> /// <param name="value">the value</param> /// <remarks> /// value converted url valid coding. /// </remarks> public void addparameter(string key, string value) { string urlencodevalue = webutility.urlencode(value); if (firstparameter) { urlstringbuilder.appendformat("?{0}={1}", key, urlencodevalue); firstparameter = false; } else { urlstringbuilder.appendformat("&{0}={1}", key, urlencodevalue); } } /// <summary> /// gets uri added paraemter /// </summary> /// <returns>the complete uri string</returns> public string geturl() { return urlstringbuilder.tostring(); } }
hope helps here @ stackoverflow. request working.
björn
if take dependency on tavis.link can use uri templates specify parameters.
[fact] public void soquestion18302092() { var link = new link(); link.target = new uri("http://www.mybase.com/get{?a,b}"); link.setparameter("a","1"); link.setparameter("b", "c"); var request = link.createrequest(); assert.equal("http://www.mybase.com/get?a=1&b=c", request.requesturi.originalstring); }
there more examples of can tavis.link on github repo.