为什么在期望POST主体中的数据时需要FromBody属性 [英] Why do I need FromBody Attribute when expecting data in POST body
问题描述
我可以将数据发送到服务器,但仅限于使用FromBody-Attribute时。
I can send my data to the server but ONLY when I use the FromBody-Attribute.
为什么不使用帖子自动从主体读取json数据?
Why is the json data not automatically read from the Body using a Post?
后端网络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中编码的查询参数。方法参数应该是简单类型(字符串,整数等)的查询参数。
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.).
复杂类型通常应该是POST表单对象。标准的ASP.NET POST请求是表单提交,例如登录时。这些请求中的参数通常编码为 application / x-www-form-urlencoded
,基本上是一串键/值对。对于复杂的参数类型,例如表单视图模型对象,这被假定为默认值。
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来自请求正文的参数 -
FromFormAttribute
- 对于来自单个表单数据字段的参数 -
FromHeaderAttribute
- 对于来自HTTP标头字段的参数 -
FromQueryAttribute
- 对于来自URL中编码的查询参数的参数 -
FromRouteAttribute
- 对于来自路径数据的参数 -
FromServicesAttribute
- 对于应在方法级注入服务的参数
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-level
这篇关于为什么在期望POST主体中的数据时需要FromBody属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!