In .Net Core API, ModelState.IsValid is not catching Required parameters

Casey Crookston

.Net Core 3.1 API. I've read a lot of threads that ask about why ModelState.IsValid isn't working as expected. Most are for web pages and not API's. And the ones I have found about API's either don't exactly apply or didn't lead me to an understanding.

I have a model that looks like this:

public class MyModel
{
    [Required(ErrorMessage = "Prop1 is required.")]
    public int Prop1 { get; set; }

    public List<int> IntList { get; set; }
}

And I have an API endpoint:

[ApiController]
[Route("api/[controller]")]
public class FooBarController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] MyModel request)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        // do stuff

        return Ok(results);

    }
}

Now, in Postman, if I pass this as the body, it works as expected:

{ "Prop1": 1001}

But if I pass this, I would expect an error of Prop1 is required. to be thrown:

{ "Prop2": 1001}

However, there is no error. The model is still valid and I just get back an empty set.

Neil

Integers have a default value of 0, therefore, once initialized, the value of prop1 will be 0, therefore it passes the [Required] test. If you make prop1 nullable, then required should catch if it is missing.

Or, if you don't want your property to be nullable, you can add a range validator:

[Required(ErrorMessage = "Prop1 is required.")]
[Range(1, int.MaxValue, ErrorMessage = "Prop1 must be greater than 0.")]
public int Prop1 { get; set; }

On a project last year, I created an attribute that was something like [NotNullOrDefault] which would work with integers being 0, or strings being null, or anything else not having it's default value.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

ASP.NET MVC Core 3.0 - Why API Request from body keeps returning !ModelState.IsValid?

ModelState.isValid()==False + Required-notation

ModelState.IsValid keeps being false because of SelectList in ASP.NET Core

ASP.NET and EF Core - ModelState.IsValid always returns true for models generated by Scaffold-DbContext

ModelState IsValid returns False Using ASP.NET Core 5 MVC Identity with UserName

ModelState.IsValid always returns false in ASP.NET Core 6.0 MVC

ModelState.IsValid is false due to the "required" navigation property in Entity

Why does ModelState.IsValid check the model properties without [Required]?

MVC ModelState.IsValid=true with a null required property

ModelState.IsValid returns False even if the required property is valid

Check modelstate content in unit test .net core web api

Inconsistent behaviour with ModelState validation asp.net core api

ModelState from ActionFilter - ASP .NET Core 2.1 API

ModelState is always valid in ASP.NET.CORE 2.2 Web Api

IsValid method is not working in custom required validation attribute in MVC and i am not using ModelState.IsValid

HttpClient 403 Catching Expired API Token .Net Core 3.1

ASP.NET Core Web API: Catching Routing Errors

Required string attribute with null value gives IsValid=true in ASP.NET Core 2 Razor Page

VB.NET - MVC ModelState.IsValid is always true

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

How ModelState.IsValid works in asp.net webapi

ModelState.IsValid is false

ModelState.isValid - false

Invoking Modelstate.isValid

ModelState stays valid even if the required attributes are empty in the .NET Framework Web API 4.7.2

Is it required to migrate WCF project to .net core API

ASP.NET Core - API multiple parameters

.Net Core API Endpoint not allowing QueryString parameters

Accept multiple parameters for API in .NET Core 2.0

TOP Ranking

HotTag

Archive