Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 997
Collin Dauphinee Avatar asked Dec 17 '18 20:12

Collin Dauphinee


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);
like image 136
Collin Dauphinee Avatar answered Oct 19 '22 09:10

Collin Dauphinee