简体   繁体   English

与 ASP.NET Core 中的 FromBody 混淆

[英]Confused with FromBody in ASP.NET Core

I have the following WEB API method, and have a SPA template with Angular:我有以下 WEB API 方法,并且有一个带有 Angular 的 SPA 模板:

[HttpPost]
public IActionResult Post([FromBody]MyViewModel model)

I thought, based on this topic, there is no need to use [FromBody] here, since I want to read the value from the message body, so there is no need to override the default behavior, but, if I don't use [FromBody] , the model that is coming from Angular is null. I'm really confused, why should I use [FromBody] , since I have used the default behavior?我想,基于这个主题,这里不需要使用[FromBody] ,因为我想从消息正文中读取值,所以不需要覆盖默认行为,但是,如果我不使用[FromBody] ,来自 Angular 的 model 是 null。我真的很困惑,我为什么要使用[FromBody] ,因为我已经使用了默认行为?

For anyone seeing this issue .net core 3 - you need to add the [ApiController] to the controller where you extend ControllerBase.对于任何看到此问题的 .net core 3 - 您需要将 [ApiController] 添加到扩展 ControllerBase 的控制器。 The [FromBody] is only needed if you're doing an MVC controller. [FromBody] 仅在您使用 MVC 控制器时才需要。

This causes the body to get automatically processed in the way you're expecting.这会导致身体以您期望的方式自动处理。

Microsoft documentation for the ApiController attribute ApiController 属性的 Microsoft 文档

The question you linked to is referring to web-api.您链接的问题是指 web-api。 You are using core-mvc which has been re-written to merge the pipelines for the previous mvc and web-api versions into one Controller class.您正在使用已重新编写的 core-mvc 以将以前的 mvc 和 web-api 版本的管道合并到一个Controller类中。

When posting json (as apposed to x-www-form-urlencoded ), the [FromBody] attribute is required to instruct the ModelBinder to use the content-type header to determine the IInputFormatter to use for reading the request.发布json (与x-www-form-urlencoded ),需要[FromBody]属性来指示ModelBinder使用内容类型标头来确定用于读取请求的IInputFormatter

For a detailed explanation of model binding to json in core-mvc, refer Model binding JSON POSTs in ASP.NET Core .有关 core-mvc 中模型绑定到 json 的详细说明,请参阅ASP.NET Core 中的模型绑定 JSON POST

And here's an alternate approach assuming you need to support both [FromForm] and [FromBody] in your Controller API…这是一种替代方法,假设您需要在控制器 API 中同时支持[FromForm][FromBody] ……

Front-End (Angular Code):前端(角度代码):

forgotPassword(forgotPassword: ForgotPassword): Observable<number> {
  const params = new URLSearchParams();
  Object.keys(forgotPassword).forEach(key => params.append(key, forgotPassword[key]));
  return this.httpClient.post(`${this.apiAuthUrl}/account/forgotpassword`, params.toString(), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });
}

Back-End (C# Code):后端(C# 代码):

[AllowAnonymous]
[HttpPost("[action]")]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { }

Now your signature can remain the same so it can support both.现在您的签名可以保持不变,因此它可以同时支持两者。

And another more permanent approach I thought about while addressing.我在解决问题时想到的另一种更持久的方法。

https://benfoster.io/blog/aspnet-core-customising-model-binding-conventions . https://benfoster.io/blog/aspnet-core-customising-model-binding-conventions

Hope it helps someone!希望它可以帮助某人!

See my discussion https://stackoverflow.com/a/75263628/5555938 on [FromBody] .请参阅我在[FromBody]上的讨论https://stackoverflow.com/a/75263628/5555938 It explains everything in great detail!它非常详细地解释了一切!

But in summary, [FromBody] does NOT accept HTML Form field name-value pairs like [FromForm] .但总而言之, [FromBody]不接受像[FromForm]这样的 HTML 表单字段名称-值对 It does NOT accept a traditional HTML form submission: It requires the following:它不接受传统的 HTML 表单提交:它需要以下内容:

  1. JavaScript POST Request manually sent to the Web API server JavaScript POST 请求手动发送到 Web API 服务器
  2. JavaScript Http Header with JSON mime-type attached JavaScript Http Header附带 JSON mime 类型
  3. JavaScript Http Body with form field extracted data, reformatted and submitted as JSON. Traditional HTML POST name-value pairs will not work! JavaScript Http Body with form field 提取数据,重新格式化并提交为 JSON。传统的 HTML POST 名称-值对将不起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET 核心 - [FromBody] 的奇怪行为 - ASP.NET Core - weird behavior with [FromBody] 是否可以在 ASP.NET Core 中结合使用 [FromRoute] 和 [FromBody]? - Is it possible to combine [FromRoute] and [FromBody] in ASP.NET Core? 在ASP.NET CORE中将属性路由值转换为Model / FromBody参数 - Attribute Routing Values into Model/FromBody Parameter in ASP.NET CORE Asp.net 核心 FromBody 总是得到 NULL - Asp.net core FromBody always getting NULL 如何在 ASP.NET Core 中结合 FromBody 和 FromForm BindingSource? - How to combine FromBody and FromForm BindingSource in ASP.NET Core? asp.net core webapi frombody 参数大小限制 - asp.net core webapi frombody parameter size limit FromBody 在 ASP.NET 核心 API 返回 null - FromBody in ASP.NET Core API returns null 在asp.net核心中调用asp.net mvc 5 Web api,FromBody始终为null - calling asp.net mvc 5 web api in asp.net core, FromBody always null 通过[FromBody]到MongoDB GeoJsonObjectModel成员的POST / PUT到ASP.Net Core始终为null - POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null 发布到 ASP.NET Core 3.1 Web 应用程序时,“[FromBody]MyClass 数据”通常为空 - When posting to an ASP.NET Core 3.1 web app, "[FromBody]MyClass data" is often null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM