作者:用户r7t3govjq0 | 来源:互联网 | 2023-05-25 19:25
我必须使用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就完成了.
1> 小智..:
虽然回答这个问题可能会迟到,但我遇到了类似的问题,以下代码对我有用.
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);
2> huysentruitw..:
您可以使用以下扩展方法:
public static class HttpClientExtensions
{
public static Task DeleteAsJsonAsync(this HttpClient httpClient, string requestUri, T data)
=> httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { COntent= Serialize(data) });
public static Task DeleteAsJsonAsync(this HttpClient httpClient, string requestUri, T data, CancellationToken cancellationToken)
=> httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { COntent= Serialize(data) }, cancellationToken);
public static Task DeleteAsJsonAsync(this HttpClient httpClient, Uri requestUri, T data)
=> httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { COntent= Serialize(data) });
public static Task DeleteAsJsonAsync(this HttpClient httpClient, Uri requestUri, T data, CancellationToken cancellationToken)
=> httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri) { COntent= Serialize(data) }, cancellationToken);
private static HttpContent Serialize(object data) => new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
}