【问题标题】:Building URI with the http client API使用 http 客户端 API 构建 URI
【发布时间】: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


【解决方案1】:

如果你依赖Tavis.Link,你可以使用URI Templates来指定参数。

    [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);
        
        
    }

Github repo 上有更多关于 Tavis.Link 的示例。

【讨论】:

    【解决方案2】:

    Flurl [披露:我是作者] 是一个可移植的类库,具有用于构建和(可选)调用 URL 的流畅 API:

    using Flurl;
    using Flurl.Http; // if you need it
    
    var url = "http://www.myBase.com"
        .AppendPathSegment("get")
        .SetQueryParams(new { a = 1, b = "c" }) // multiple
        .SetQueryParams(dict)                   // multiple with an IDictionary
        .SetQueryParam("name", "value")          // one by one
    
        // if you need to call the URL with HttpClient...
    
        .WithOAuthBearerToken("token")
        .WithHeaders(new { a = "x", b = "y" })
        .ConfigureHttpClient(client => { /* access HttpClient directly */ })
        .PostJsonAsync(new { first_name = firstName, last_name = lastName });
    

    Querystring 值在每种情况下都是 URL 编码的。 Flurl 还包括一组漂亮的HTTP testing features。 NuGet 上提供了完整的包:

    PM&gt; Install-Package Flurl.Http

    或只是独立的 URL 构建器:

    PM&gt; Install-Package Flurl

    【讨论】:

      【解决方案3】:

      查询字符串:

      写入数据:

      Server.Transfer("WelcomePage.aspx?FirstName=" + Server.UrlEncode(fullName[0].ToString()) +
                                              "&LastName=" + Server.UrlEncode(fullName[1].ToString()));
      

      获取写入的数据:

      Server.UrlDecode(Request.QueryString["FirstName"].ToString()) + " "
                                                      + Server.UrlDecode(Request.QueryString["LastName"].ToString());
      

      【讨论】:

      • 如果您有特定代码或特定要求,请在此处注明。
      猜你喜欢
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多