【问题标题】:Add Params HttpClient C#添加参数 HttpClient C#
【发布时间】:2019-11-18 04:17:36
【问题描述】:

我想加一个参数,但我也有一个body,我想形成这种格式:

HttpPost

http://localhost:8080/master/public/api/v1/invoice/send?token=123456

目前我有:

HttpPost
http://localhost:8080/master/public/api/v1/invoice/send

 private readonly string UrlBase = "http://localhost:8080";
 private readonly string ServicePrefix = "master/public/api";



public async Task<DocumentResponse> SendInvoice<T>(Invoice body)
            {
            string controller = "/v1/invoice/send";
            try
            {

                var request = JsonConvert.SerializeObject(body);

                var content = new StringContent(
                    request, Encoding.UTF8,
                    "application/json");
                var client = new HttpClient();



                client.BaseAddress = new Uri(UrlBase);
                var url = string.Format("{0}{1}", ServicePrefix, controller);
                var response = await client.PostAsync(url, content);
                Debug.WriteLine(response);
                var result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return new DocumentResponse
                    {

                    };
                }
                var list = JsonConvert.DeserializeObject<DocumentResponse>(result);
                return list;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return new DocumentResponse
                {

                };
            }
        }

当我直接将它添加到url时,请求失败。

进阶

当我直接将它添加到 url 时,请求失败。 查询HttpClient,我发现了这个,但是如何添加它有一个body?

var parameters = new Dictionary<string, string> { { "token", "123456" } };
var encodedContent = new FormUrlEncodedContent (parameters);

参考:C#: HttpClient with POST parameters

谢谢

【问题讨论】:

  • 这绝对是可行的。您可以搜索 [FromBody] 和 [FromQuery] 了解更多详情。 FromBody 映射到您的请求正文,FromQuery 映射到查询字符串参数。
  • 免责声明:我是该库的作者,您可以使用 RetroCoreFit,github.com/neurospeech/asp-net-core-extensions/blob/master/…,它可以让您更好地控制 REST api 的通信

标签: c# api post dotnet-httpclient


【解决方案1】:

当你格式化你的 URL 时,你需要像这样添加参数:

var url = string.Format("{0}{1}", ServicePrefix, controller);

url = string.Format("{0}?token=123456", url);

注意 URL 和查询参数之间的?。

您没有指定如何在方法中获取 token 的值,但如果它是类似于 ServicePrefix 的 readonly 值,您可以将其作为参数传递给 string.Format:

var url = string.Format("{0}{1}", ServicePrefix, controller);

url = string.Format("{0}?token={1}", url, Token);

你总是可以把它放在一行,但我已经把它分开了,以便于阅读:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多