为什么在 POST body 中期望数据时需要 FromBody 属性

Why do I need FromBody Attribute when expecting data in POST body

我可以将我的数据发送到服务器,但仅当我使用 FromBody-Attribute 时。

为什么 json 数据不能使用 Post 从 Body 中自动读取?

后台网站api

[HttpPost]
public async Task<IActionResult> Post([FromBody]CreateSchoolyearRequestDTO dto)
{

}

前端 angularjs

this.createSchoolyear = function (schoolyear) {
  var path = "/api/schoolyears";
  return $http({
      url: path,
      method: "POST",
      data:  schoolyear,
      contentType: "application/json"
  }).then(function (response) {
      return response;
  });
};

只是因为某些东西是 POST 请求,所以没有明确的规则如何传递参数。 POST 请求仍然可以包含在 URL 中编码的查询参数。方法参数应该是“简单”类型(字符串、整数等)的查询参数。

复杂类型通常应 POST 形式 objects。标准 ASP.NET POST 请求是一个表单提交,例如登录时。这些请求中的参数通常编码为 application/x-www-form-urlencoded,基本上是一串 key/value 对。对于复杂的参数类型,例如表单视图模型 objects,这是假定的默认值。

对于所有其他 non-default 情况,您需要明确说明方法参数的来源以及它在请求中的传输方式。为此,有许多不同的属性:

  • FromBodyAttribute – 对于来自请求的参数 body
  • FromFormAttribute – 对于来自单个表单数据字段的参数
  • FromHeaderAttribute – 对于来自 HTTP header 字段的参数
  • FromQueryAttribute – 对于来自在 URL
  • 中编码的查询参数的参数
  • FromRouteAttribute – 对于来自路由数据的参数
  • FromServicesAttribute – 对于应该在 method-level
  • 注入服务的参数