I use [EmailAddress] attribute to validate email on server side. However, when I send an invalid email address, I receive a 400 status code response with no message instead of getting into my action method and seeing a ModelState Error.
Debug output simply says that Microsoft.AspNetCore.Mvc.SerializableError is thrown.
Could anyone explain this, please?
Model:
public class LoginVm
{
[Required(ErrorMessage = "Email cannot be empty.")]
[EmailAddress(ErrorMessage = "Email has an incorrect format.")]
public string Email { get; set; }
[Required(ErrorMessage = "Password cannot be empty.")]
public string Password { get; set; }
}
Action:
[AllowAnonymous]
[HttpPost]
public IActionResult Authenticate([FromBody]LoginVm loginVm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (loginVm.Email != "maksym@no.no" || loginVm.Password != "password")
{
return NotFound("There is no such user.");
}
return Ok();
}
Debug output:
Request:
POST http://localhost:58072/api/accounts HTTP/1.1
Host: localhost:58072
Connection: keep-alive
Content-Length: 47
Accept: application/json, text/plain, */*
Origin: https://localhost:44381
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
Content-Type: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
{"email":"wrongemail","password":"wrongpassword"}
The [ApiController]
attribute provides Automatic HTTP 400 responses .
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
Validation errors automatically trigger an HTTP 400 response. The following code becomes unnecessary in your actions:
if (!ModelState.IsValid) { return BadRequest(ModelState); }
How to turn off this feature
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.