.NET Core Web API:多个 [FromBody]? [英] .NET Core Web API: multiple [FromBody]?

查看:57
本文介绍了.NET Core Web API:多个 [FromBody]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将用 ASP.NET MVC 编写的代码转换为 ASP.NET Core MVC.在转换代码时,我遇到了一个问题.我们使用了一个具有多个参数的方法,如下所示:

I am converting code that was written in ASP.NET MVC to ASP.NET Core MVC. While I was converting the code, I encountered a problem. We used a method that has multiple parameters like this:

[HttpPost]                                                      
public class Search(List<int> ids, SearchEntity searchEntity)           
{   
  //ASP.NET MVC                                                                   
}

但是在 .NET Core 中编码时,ids 参数为 null.

But when coding this in .NET Core, the ids parameter is null.

[HttpPost]                                                      
public class Search([FromBody]List<int> ids,[FromBody]SearchEntity searchEntity)           
{   
  //ASP.NET Core MVC                                                                   
} 

当我将ids 参数放在SearchEntity 类中时,没有问题.但是我有很多方法都是这样写的.我该怎么办?

When I place the ids parameter in the SearchEntity class, there is no problem. But I have lots of methods that are written like this. What can I do about this problem?

推荐答案

只能有一个FromBody,因为body只能被读取一次

Can only have one FromBody as the body can only be read once

参考 模型绑定ASP.NET 核心

每个动作最多可以有一个由 [FromBody] 修饰的参数.ASP.NET Core MVC 运行时将读取请求流的责任委托给格式化程序.一旦为参数读取了请求流,通常不可能再次读取请求流以绑定其他[FromBody] 参数.

There can be at most one parameter per action decorated with [FromBody]. The ASP.NET Core MVC run-time delegates the responsibility of reading the request stream to the formatter. Once the request stream is read for a parameter, it's generally not possible to read the request stream again for binding other [FromBody] parameters.

MVC Core 在如何将模型绑定到操作上更加严格.当您想要自定义绑定行为时,您还必须明确指出要从何处绑定数据.

MVC Core is stricter on how to bind model to actions. You also have to explicitly indicate where you want to bind the data from when you want to customize binding behavior.

这篇关于.NET Core Web API:多个 [FromBody]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆