ASP.NET Core服务器端验证失败导致Microsoft.AspNetCore.Mvc.SerializableError

时间:2018-07-13 16:02:31

标签: c# asp.net .net asp.net-mvc .net-core

我使用[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();
    }

调试输出:

  • Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 POST http://localhost:44381/api/accounts application / json 43 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行成功。
  • Microsoft.AspNetCore.Server.Kestrel:信息:连接ID为“ 0HLF8QUE7VV6T”,请求ID为“ 0HLF8QUE7VV6T:00000004”:应用程序已完成,没有读取整个请求正文。
  • Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:路由与{action =“ Authenticate”,controller =“ Account”,page =“”}匹配。执行动作WebApp.Controllers.AccountController.Authenticate(WebApp)
  • “ dotnet.exe”(CoreCLR:clrhost):已加载“ C:\ Program Files \ dotnet \ shared \ Microsoft.NETCore.App \ 2.1.1 \ System.Runtime.Serialization.Primitives.dll”。跳过的加载符号。模块已优化,调试器选项“仅我的代码”已启用。
  • “ dotnet.exe”(CoreCLR:clrhost):已加载“ C:\ Program Files \ dotnet \ shared \ Microsoft.NETCore.App \ 2.1.1 \ System.Data.Common.dll”。跳过的加载符号。模块已优化,调试器选项“仅我的代码”已启用。
  • Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor:信息:执行ObjectResult,写入类型为“ Microsoft.AspNetCore.Mvc.SerializableError”的值。
  • Microsoft.AspNetCore.Mvc.Internal.ControllerActionActionInvoker:信息:在78.8614毫秒内执行了操作WebApp.Controllers.AccountController.Authenticate(WebApp)
  • Microsoft.AspNetCore.Hosting.Internal.WebHost:Information:请求在96.9303ms中完成400 application / json; charset = utf-8

请求:

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"}

1 个答案:

答案 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;
    });

    ...
}