How can I prevent ASP.NET Core from marking model

2020-04-08 07:19发布

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.

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.

Is there any way I can make ASP.NET Core handle empty request bodies more gracefully and not mark the model state as invalid?

1条回答
你好瞎i
2楼-- · 2020-04-08 07:39

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);
查看更多
登录 后发表回答