我必须使用 HttpClient 类向包含 JSON 内容的 REST API 服务发送删除命令,但无法正常工作。
API 调用:
DELETE /xxx/current
{
"authentication_token": ""
}
因为我无法在下面的语句中添加任何内容:
HttpResponseMessage response = client.DeleteAsync(requestUri).Result;
我知道如何使用 RestSharp 完成这项工作:
var request = new RestRequest {
Resource = "/xxx/current",
Method = Method.DELETE,
RequestFormat = DataFormat.Json
};
var jsonPayload = JsonConvert.SerializeObject(cancelDto, Formatting.Indented);
request.Parameters.Clear();
request.AddHeader("Content-type", "application/json");
request.AddHeader ("Accept", "application/json");
request.AddParameter ("application/json", jsonPayload, ParameterType.RequestBody);
var response = await client.ExecuteTaskAsync (request);
但我在没有 RestSharp 的情况下完成了它。
最佳答案
虽然现在回答这个问题可能有点晚了但是 我遇到过类似的问题,以下代码对我有用。
HttpRequestMessage request = new HttpRequestMessage
{
Content = new StringContent("[YOUR JSON GOES HERE]", Encoding.UTF8, "application/json"),
Method = HttpMethod.Delete,
RequestUri = new Uri("[YOUR URL GOES HERE]")
};
await httpClient.SendAsync(request);
.NET 5 更新
.NET 5 引入了 JsonContent。这是使用 JsonContent 的扩展方法:
public static async Task<HttpResponseMessage> DeleteAsJsonAsync<TValue>(this HttpClient httpClient, string requestUri, TValue value)
{
HttpRequestMessage request = new HttpRequestMessage
{
Content = JsonContent.Create(value),
Method = HttpMethod.Delete,
RequestUri = new Uri(requestUri, UriKind.Relative)
};
return await httpClient.SendAsync(request);
}
关于c# - 如何使用 HttpClient 将带有 JSON 的 DELETE 发送到 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054515/