我必须使用动态查询字符串构建URI地址,并寻找通过代码构建它们的舒适方法。使用http客户端API构建URI
我浏览了System.Net.Http程序集,但没有发现这种情况下的类或方法。这个API不提供这个吗?我在StackOverflow的搜索结果使用了System.Web中的HttpUtility类,但我不想在我的类库中引用任何ASP.Net组件。
我需要这样一个URI:http://www.myBase.com/get?a=1&b=c。
在此先感谢您的帮助!
更新(2013年9月8日):
我的解决方案是创建一个使用System.Net.WebUtilitiy类编码值的URI生成器(进口NuGet包遗憾的是没有提供强名称键)。 这里是我的代码:
/// <summary>
/// Helper class for creating a URI with query string parameter.
/// </summary>
internal class UrlBuilder
{
private StringBuilder UrlStringBuilder { get; set; }
private bool FirstParameter { get; set; }
/// <summary>
/// Creates an instance of the 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 a new parameter to the URI
/// </summary>
/// <param name="key">the key </param>
/// <param name="value">the value</param>
/// <remarks>
/// The value will be converted to a 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 the URI with all previously added paraemter
/// </summary>
/// <returns>the complete URI as a string</returns>
public string GetUrl()
{
return UrlStringBuilder.ToString();
}
}
希望这有助于在这里有人在StackOverflow上。我的请求正在工作。
比约恩
也许这http://msdn.microsoft.com/en-us/ library/system.uri.aspx –
也许'System.Net.WebUtility'? – I4V
System.Net.WebUtility可以帮助我将字符串解码为有效的URI。但是我仍然需要自己创建URL,对吗? – Bjoern