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

查看:1533
本文介绍了.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                                                                   
} 

当我放置< SearchEntity 类中的code> ids 参数,没有问题。但是我有很多这样写的方法。我该怎么办?

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 因为正文只能读取一次

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

参考 ASP.NET Core中的模型绑定


每个操作最多只能有一个用 [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天全站免登陆