【问题标题】:how to pass query parameter and path paramter in .net http client getasyn method如何在.net http客户端getasync方法中传递查询参数和路径参数
【发布时间】:2019-07-29 15:04:39
【问题描述】:

我需要将查询参数和路径参数传递给 .NET 中的 HttpClient GetAsync() 方法

文件/{document_id}?version={version_number}

[Route("api/drs/v1/document/getdetails/{Id}")]
[HttpGet]
public async Task<HttpResponseMessage> DocumentDetails(HttpRequestMessage details)
{
    // Debugger.Launch();
    try
    {
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Clear();

            //String path=Request.Url.GetLeftPart(UriPartial.Path);
            HttpResponseMessage response = await client.GetAsync("http://localhost:8089/api/drs/v1/document/getdetail/"]);

            if (response.IsSuccessStatusCode)
            {
                Console.Write("Success");
            }
            else
            {
                Console.Write("Failure");
            }

            return response;
        }
    }
    catch (Exception e)
    {
        throw e;
    }
}

我无法在 GetAsync() 方法中同时传递参数

【问题讨论】:

  • 查询参数是URL的一部分,这部分叫做Query string

标签: c# httpclient


【解决方案1】:

尝试使用下一个扩展方法来构建您的网址。您可以传递您需要的基本 url、路径和参数字典。

    public static Uri BuildUri(string baseUrl, string path, Dictionary<string, string> queryParams = null)
    {
        var uriBuilder = new UriBuilder(baseUrl) {Path = path};

        if (queryParams != null)
        {
            var query = string.Join("&", queryParams.Select(x => $"{x.Key}={x.Value}").ToArray());
            uriBuilder.Query = query;
        }

        return uriBuilder.Uri;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多