我有一个场景,我需要调用构造如下的Web API Delete方法:
// DELETE: api/products/{id}/headers
[HttpDelete("{id}/headers")]
public void DeleteProductHeaders(int id, [FromBody] string query)
{
}诀窍是为了得到查询,我需要通过主体发送它,而DeleteAsync没有像post那样的json参数。有人知道如何在c#中使用System.Net.Http客户端完成此操作吗?
// Delete a product's headers
public void DeleteProductHeaders(int id, string query)
{
using (var client = GetClient())
{
HttpResponseMessage response;
try
{
// HTTP DELETE
response = client.DeleteAsync($"api/products/{id}/headers").Result;
}
catch (Exception ex)
{
throw new Exception("Unable to connect to the server", ex);
}
}
return retVal;
}发布于 2017-10-17 07:41:38
下面是我是如何完成的
var request = new HttpRequestMessage(HttpMethod.Delete, "http://www.example.com/");
request.Content = new StringContent(JsonConvert.SerializeObject(object), Encoding.UTF8, "application/json");
await this.client.SendAsync(request);发布于 2016-08-16 22:08:45
我认为这样设计HttpClient的原因是尽管HTTP1.1规范允许DELETE请求上的消息体,但本质上它不会这样做,因为规范没有为它定义任何语义,因为它是定义为here的。HttpClient严格遵循HTTP规范,因此您可以看到它不允许向请求添加消息体。
因此,我认为您在客户端的选择包括使用here中描述的HttpRequestMessage。如果你想从后端修复它,如果你的消息体可以在查询参数中很好地工作,你可以尝试这样做,而不是在消息体中发送查询。
我个人认为DELETE应该被允许有一个消息体,并且在服务器中不应该被忽略,因为像你在这里提到的那样,肯定有这样的用例。
在任何情况下,有关这方面的更有成效的讨论,请查看this。
发布于 2018-07-06 16:56:25
我的接口如下:
// DELETE api/values
public void Delete([FromBody]string value)
{
}从C#服务器端调用
string URL = "http://localhost:xxxxx/api/values";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "DELETE";
request.ContentType = "application/json";
string data = Newtonsoft.Json.JsonConvert.SerializeObject("your body parameter value");
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
try
{
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
}
catch
{
}https://stackoverflow.com/questions/38976260
复制相似问题