Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用http客户端API构建URI_C#_.net_Dotnet Httpclient - Fatal编程技术网

C# 使用http客户端API构建URI

C# 使用http客户端API构建URI,c#,.net,dotnet-httpclient,C#,.net,Dotnet Httpclient,我必须用动态查询字符串构建一个URI地址,并寻找一种通过代码轻松构建它们的方法 我浏览了System.Net.Http程序集,但没有找到适用于本例的类或方法。这个API不提供这个吗?我在StackOverflow的搜索结果使用System.Web中的HttpUtility类,但我不想引用类库中的任何ASP.Net组件 我需要这样的URI: 提前感谢您的帮助 更新(2013/9/8): 我的解决方案是创建一个URI生成器,它使用System.Net.WebUtility类对值进行编码(很遗憾,导入

我必须用动态查询字符串构建一个URI地址,并寻找一种通过代码轻松构建它们的方法

我浏览了System.Net.Http程序集,但没有找到适用于本例的类或方法。这个API不提供这个吗?我在StackOverflow的搜索结果使用System.Web中的HttpUtility类,但我不想引用类库中的任何ASP.Net组件

我需要这样的URI:

提前感谢您的帮助

更新(2013/9/8):

我的解决方案是创建一个URI生成器,它使用System.Net.WebUtility类对值进行编码(很遗憾,导入的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();
    }
}
//
///用于创建带有查询字符串参数的URI的帮助器类。
/// 
内部类UrlBuilder
{
私有StringBuilder UrlStringBuilder{get;set;}
私有布尔第一参数{get;set;}
/// 
///创建UriBuilder的实例
/// 
///基址(例如:http://localhost:12345)
公共URL生成器(字符串baseUrl)
{
UrlStringBuilder=新的StringBuilder(baseUrl);
FirstParameter=true;
}
/// 
///将新参数添加到URI
/// 
///钥匙
///价值
/// 
///该值将转换为url有效编码。
/// 
public void AddParameter(字符串键、字符串值)
{
字符串urlEncodeValue=WebUtility.UrlEncode(值);
if(第一个参数)
{
AppendFormat(“?{0}={1}”,键,urlEncodeValue);
FirstParameter=false;
}
其他的
{
AppendFormat(&{0}={1}),键,urlEncodeValue);
}
}
/// 
///获取包含以前添加的所有参数的URI
/// 
///作为字符串的完整URI
公共字符串GetUrl()
{
返回UrlStringBuilder.ToString();
}
}
希望这对StackOverflow的人有所帮助。我的请求有效

比约恩查询字符串:

要写入数据:

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());
查询字符串:

要写入数据:

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

如果依赖于,则可以使用来指定参数

    [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上还有一些关于Tavis.Link的例子。

如果依赖于,可以使用它来指定参数

    [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上还有一些关于Tavis.Link的例子。

[披露:我是作者]是一个可移植类库,具有用于构建和(可选)调用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 });
查询字符串值在每种情况下都是URL编码的。Flurl还包括一组漂亮的。NuGet上提供了完整的软件包:

PM>安装软件包Flurl.Http

或者仅使用独立的URL生成器:

PM>Install Package 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 });
查询字符串值在每种情况下都是URL编码的。Flurl还包括一组漂亮的。NuGet上提供了完整的软件包:

PM>安装软件包Flurl.Http

或者仅使用独立的URL生成器:


PM>Install Package Flurl

这可能是
System.Net.WebUtility
?System.Net.WebUtility可以帮助我将字符串解码为有效的URI。但是我仍然需要自己构建URL,对吗?谢谢Alessandro,我已经在使用URI类了。但是如何处理参数呢?URI生成器更适合静态参数。这可能是
System.Net.WebUtility
?System.Net.WebUtility可以帮助我将字符串解码为有效的URI。但是我仍然需要自己构建URL,对吗?谢谢Alessandro,我已经在使用URI类了。但是如何处理参数呢?URI生成器更适合静态参数。如果您有特定代码或特定要求,请在此处注明。如果您有特定代码或特定要求,请在此处注明。