【发布时间】:2014-08-01 23:32:02
【问题描述】:
我必须使用动态查询字符串构建一个 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 的某些人有所帮助。我的请求有效。
比约恩
【问题讨论】:
-
可能是
System.Net.WebUtility? -
System.Net.WebUtility 可以帮助我将字符串解码为有效的 URI。但我还是得自己构建 URL,对吧?
-
谢谢 Alessandro,我已经在使用 URI 类了。但是如何处理参数呢? URI Builder 用于静态参数。
标签: c# .net dotnet-httpclient