How can I prevent ASP.NET Core from marking model state as invalid on empty request bodies?

Viewed 2383

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 Answers

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);
Related