2013-08-18 91 views
1

我必须使用动态查询字符串构建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上。我的请求正在工作。

比约恩

+0

也许这http://msdn.microsoft.com/en-us/ library/system.uri.aspx –

+0

也许'System.Net.WebUtility'? – I4V

+0

System.Net.WebUtility可以帮助我将字符串解码为有效的URI。但是我仍然需要自己创建URL,对吗? – Bjoern

回答

2

如果采取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); 


    } 

有,你可以与Tavis.Link在Github上repo做一些更多的例子。

0

查询字符串:

要写入数据:

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()); 
+0

如果您有特定的代码或特定的要求,请在此处注明它们。 – Jacob

2

Flurl [披露:我是作者]是便携式类库运动用于构建一个流利API和(可选地)调用的URL:

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

查询字符串的值是URL编码在每种情况下。 Flurl还包括一套漂亮的HTTP testing features。全包,请访问的NuGet:

PM> Install-Package Flurl.Http

或仅仅是独立的URL生成器:

PM> Install-Package Flurl

+0

干得好!我会尝试在我的oss项目中使用它 –