Pascal
Pascal

Reputation: 12855

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

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

Upvotes: 14

Views: 10253

Answers (1)

poke
poke

Reputation: 387617

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

Upvotes: 24

Related Questions