ardalis / ApiEndpoints

A project for supporting API Endpoints in ASP.NET Core web applications.
MIT License
3.13k stars 227 forks source link

ModelState is always Valid #167

Closed babaktaremi closed 2 years ago

babaktaremi commented 2 years ago

Hi I'm using the latest version on NET6 and using RequiredAttribute on request models. But the ModelState is always valid. What seems to be the problem?

ardalis commented 2 years ago
  1. Which version is latest? v3 or v4-prerelease?
  2. Can you show your endpoint and its associated request model?
babaktaremi commented 2 years ago
  1. Which version is latest? v3 or v4-prerelease?
  2. Can you show your endpoint and its associated request model?

I Created a NET 6 Template and added to following code to the Program.cs class to suppress the default behaviour of modelstate validation in asp. net core

builder.Services.AddControllers().ConfigureApiBehaviorOptions(c => c.SuppressModelStateInvalidFilter = true);

then I Created a simple model for login

public class LoginRequest
    {
        [Required]
        public string UserName { get; set; }

        [Required]
        public string Password { get; set; }
    }

and the related endpoint like this

  [ApiController]
    [Route("Api/User")]
    public class Login:BaseAsyncEndpoint.WithRequest<LoginRequest>.WithoutResponse
    {
        [HttpPost("Login")]
        public override async Task<ActionResult> HandleAsync(LoginRequest request, CancellationToken cancellationToken = new CancellationToken())
        {
            if (!ModelState.IsValid)
                return BadRequest("Not Valid");

            return Ok("Valid");
        }
    }

The Value of ModelState.IsValid is always true. regardless of the state of the LoginRequest properties. the version I'm currently using is 3.1.0

ardalis commented 2 years ago

Why are you suppressing model state invalid? Given that you're doing that, isn't this behaving as expected?

ardalis commented 2 years ago

Let me know if this is still an issue - closing for now.