添加参数 HttpClient C#

Add Params HttpClient C#

我想加一个参数,但是我还有一个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);

参考:

谢谢

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

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

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

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

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

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

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

你总是可以把它放在一行上,但我把它分开了,这样更容易阅读:-)