I believe the issue is with the null values. I have tested payloads that contained values such as
{
name: 'My Name',
householdSize: '3'
}
and the server would get the request. However, I want to still allow users to not input any data, however, when this occurs, the server is never hit (I have a breakpoint to test).
I am using a js frontend with a .NET Core Web API.
I have a payload that looks like
{
name: null,
householdSize: null
}
My view model is as such
public class MyViewModel
{
[Required]
public string Name { get; set; }
[Required]
public EHouseholdSize HouseholdSize { get; set; }
public enum EHouseholdSize
{
One = 1,
Two,
Three,
Four,
FivePlus
}
}
My controller is as such
public async Task<IActionResult> Add([FromBody]QuestionnaireViewModel viewModel)
{
if(!ModelState.IsValid)
{
return BadRequest();
}
// Do stuff
return Ok();
}
CodePudding user response:
Your ModelState
is not valid when sending null
values because both of the property of your view model has [Required]
attribute. Sending {"name": null, "houseHoldSize": null}
is equivalent to `` or {}
.
Therefore, not fulfilling the requirements and makes the model state invalid. That's why it's never pass your if block.
So if you want to allow posting null or empty values, you need to remove the [Required]
attribute from your ViewModel properties.
CodePudding user response:
When you use API Controller (has [ApiController] attribute), the action parameters will be automaticaly validated and you don' t need if ( !ModelState.IsValid ) since it will never be hitted if model state is invalid. Api controller will return BadRequest before it. So remove the [Required] attribute from your ViewModel properties or make them not null
Another thing is if your project has enabled nullable (mostly net 6 projects)
<Nullable>enable</Nullable>
you will need to make a property Name nullable too
public string? Name { get; set; }
Otherwise you will get a BadRequest "The Name field is required.", even if you remove [Required] attribute.
CodePudding user response:
Note that I found I can supress this auto 400 code by doing this on the Startup
services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
});