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

白昼怎懂夜的黑 提交于 2019-11-29 13:07:59

问题


I can send my data to the server but ONLY when I use the FromBody-Attribute.

Why is the json data not automatically read from the Body using a Post?

Backend web api

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

}

Frontend 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;
  });
};

回答1:


Just because something is a POST request, there is no clear rule how arguments are being transferred. A POST request can still contain query parameters encoded in the URL. A method parameter is expected to be a query parameter for “simple” types (strings, ints, etc.).

Complex types are usually expected to be POST form objects. The standard ASP.NET POST request is a form submit, e.g. when logging in. The parameters in those request are usually encoded as application/x-www-form-urlencoded, basically a string of key/value pairs. For complex parameter types, e.g. form view model objects, this is assumed the default.

For all other non-default situations, you need to be explicit where a method parameter comes from, how it is being transferred in the request. For that purpose, there are a number of different attributes:

  • FromBodyAttribute – For parameters that come from the request body
  • FromFormAttribute – For parameters that come from a single form data field
  • FromHeaderAttribute – For parameters that come from a HTTP header field
  • FromQueryAttribute – For parameters that come from a query argument encoded in the URL
  • FromRouteAttribute – For parameters that come from the route data
  • FromServicesAttribute – For parameters for which services should be injected at method-level


来源:https://stackoverflow.com/questions/34529346/why-do-i-need-frombody-attribute-when-expecting-data-in-post-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!