如何防止ASP.NET Core在空请求主体上将模型状态标记为无效? [英] How can I prevent ASP.NET Core from marking model state as invalid on empty request bodies?
问题描述
我有一个从请求主体接收参数的动作.客户端使用二进制格式使用此API,该格式可能会将请求模型序列化为空主体.
I have an action that receives parameters from the request body. Clients are hitting this API using a binary format that can potentially serialize request models into an empty body.
如果我使用空的请求正文敲击这些操作之一,则该操作将使用请求模型的默认值(即null
)进行调用,但模型状态会标记为无效.通常这是可以的,但是如果模型状态无效,我有一个中间件会响应并显示错误.
If I hit one of these actions with an empty request body, the action is invoked with a default value (i.e. null
) for the request model, but the model state is marked as invalid. This would normally be okay, but I have a middleware that responds with an error if the model state is invalid.
有什么方法可以使ASP.NET Core更优雅地处理空的请求主体,并且不将模型状态标记为无效?
Is there any way I can make ASP.NET Core handle empty request bodies more gracefully and not mark the model state as invalid?
推荐答案
浏览ASP.NET Core源代码后,我发现MvcOptions
具有控制此行为的属性:
After hunting through the ASP.NET Core source code, I found that MvcOptions
has a property to control this behavior:
services.AddMvc()
.AddMvcOptions(o => o.AllowEmptyInputInBodyModelBinding = true);
这篇关于如何防止ASP.NET Core在空请求主体上将模型状态标记为无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!