【发布时间】: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