【问题标题】:Reason behind GET/DELETE cannot have body in webapiGET/DELETE 背后的原因在 webapi 中不能有正文
【发布时间】:2014-11-05 04:07:52
【问题描述】:

为什么HttpMethods如GETDELETE不能包含body

public Task<HttpResponseMessage> GetAsync(Uri requestUri);
public Task<HttpResponseMessage> DeleteAsync(string requestUri);

同样在 Fiddler 中,如果我提供一个主体,背景会变为红色。但它仍然会在 body 上执行。

因此,作为替代方案,我使用了SendAsync(),因为它接受HttpRequestMessage,其中可以包含HttpMethod 以及内容

// other codes
Category category = new Category(){ Description = "something" };
string categoryContent = JsonConvert.SerializeObject(category);
string type = "application/json";

HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Delete, "-page-")
HttpContent content = new StringContent(categoryContent, Encoding.UTF8, type);
HttpClient client = new HttpClient();

message.Content = content;
await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead);
// other codes

我错过了什么吗?

【问题讨论】:

标签: c# asp.net-web-api


【解决方案1】:

根据 HTTP 标准,GET 方法旨在检索数据,因此无需提供请求正文。

添加请求正文违反了定义的规则。因此这是被禁止的。

同样适用于 DELETE 方法。

【讨论】:

  • 由于 HTTP 1.1 Delete 可以有一个主体,它并不总是被处理。更多信息请参见this answer
猜你喜欢
  • 2018-10-25
  • 2013-12-18
  • 2021-11-01
  • 2019-02-14
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2011-01-31
  • 2011-01-15
相关资源
最近更新 更多