.NET Core MVC Parameter Validation

Viewed 112

I'm working on making sign-in method with .net core mvc with EF.

[HttpPost("/login")]
public IActionResult SignIn(SignInDto param)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(
            Json
            (
                new SignInResponse
                {
                    Message = "Bad Request"
                }
            )
        );
    }
}

...

public class SignInDto
{
    [StringLength(50)]
    [Required]
    public string username;

    [Required]
    [StringLength(50)]
    public string password;
}

I have a user model. but two data username and password are used when sign-in.

So I made a SignInDto class.

But ModelState.IsValid always returns True even when parameter is empty.

I printed params. they were emtpy.

What did I do wrong?

1 Answers

Simply needed to change your class:-

public class SignInDto
{
    [Required]
    [StringLength(50)]
    public string username { get; set; }

    [Required]
    [StringLength(50)]
    public string password { get; set; }
}

it should work fine. Actually, The validator ignores the [RequiredAttribute] on fields - it takes into account only properties.

Related