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;
});
};
The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.
The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.
The [FromBody] attribute can be applied on only one primitive parameter of an action method. It cannot be applied to multiple primitive parameters of the same action method.
[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.
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 bodyFromFormAttribute
– For parameters that come from a single form data fieldFromHeaderAttribute
– For parameters that come from a HTTP header fieldFromQueryAttribute
– For parameters that come from a query argument encoded in the URLFromRouteAttribute
– For parameters that come from the route dataFromServicesAttribute
– For parameters for which services should be injected at method-levelIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With