我使用[EmailAddress]属性在服务器端验证电子邮件。但是,当我发送无效的电子邮件地址时,会收到没有消息的400状态代码响应,而不是进入我的操作方法并看到ModelState错误。
Debug输出仅表明Microsoft.AspNetCore.Mvc.SerializableError被抛出。
请问有人可以解释吗?
型号:
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; }
}
操作:
[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();
}
调试输出:
请求:
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"}
答案 0 :(得分:8)
[ApiController]
属性提供Automatic HTTP 400 responses。
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
验证错误会自动触发HTTP 400响应。的 以下代码在您的操作中变得不必要:
if (!ModelState.IsValid) { return BadRequest(ModelState); }
如何关闭此功能
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
...
}