.NET 对使用正文内容的 DELETE 请求不满意。使用我正在集成的 API,请求看起来像是正在发送,但响应总是超时。 WebClient 和 HttpClient 都会发生这种情况。 API 开发人员在其端看到请求并响应 200,但 HttpClient 未收到响应并超时。他们的 API def 有效,因为我已经使用邮递员和其他请求工具实现了它。
我尝试添加各种请求/响应标头。直接使用 HttpClient 和 WebRequest。我希望 API 能够做出任何回应。
DeleteWithPostAsync(string url, string json)
{
HttpRequestMessage request = new
HttpRequestMessage(HttpMethod.Delete, url)
{
Content = new StringContent(json, Encoding.UTF8,
"application/json"),
};
var result = await
client.SendAsync(request).ConfigureAwait(false);
var response = await
result.Content.ReadAsStringAsync().ConfigureAwait(false);
return response;
}
.NET 在 WebApi 中发送和接收数据作为 DELETE 方法的响应时绝对没有问题。
这里是一个工作片段,您可以将其插入到控制器上,您只需使用
dotnet new webapi
即可创建。
我添加了一个 DELETE 方法,该方法采用
MyClass
类型的对象类并返回在另一个对象中提交的数据。
// this is an arbitrary class to send to DELETE method
public class MyClass
{
public string Username { get; set; }
}
// this is your code but with data and internal DELETE URL to call
[HttpGet("/stackoverflow/try")]
public async Task<object> DeleteWithPostAsync()
{
// change this accordin with your local domanin and port
var domainAndPort = "http://localhost:1234";
var client = new HttpClient();
//client.Timeout = TimeSpan.FromSeconds(10);
HttpRequestMessage request = new
HttpRequestMessage(HttpMethod.Delete,
$"{domainAndPort}/stackoverflow/delete")
{
Content = new StringContent("{\"Username\": \"kiggyttass\"}", Encoding.UTF8,
"application/json")
};
var result = await
client.SendAsync(request).ConfigureAwait(false);
var response = await
result.Content.ReadAsStringAsync().ConfigureAwait(false);
return response;
}
// this simulates the delete API you call
[HttpDelete("/stackoverflow/delete")]
public object DeletionAsync([FromBody] MyClass json)
{
var obj = new
{
Message = $"Hey {json.Username}! deletion operation was completed successfully",
Details = "No problems with that"
};
return Ok(obj);
}
当您调用 GET
/stackoverflow/try
方法时,它会调用 DELETE 方法并返回您想要的响应,如下所示:
{"message":"Hey kiggyttass! deletion operation was completed successfully","details":"No problems with that"}
希望有帮助! 科斯贝儿!