简体   繁体   中英

ASP.NET Core server side validation failure causes Microsoft.AspNetCore.Mvc.SerializableError

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:

  • Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44381/api/accounts application/json 43 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution successful.
  • Microsoft.AspNetCore.Server.Kestrel:Information: Connection id "0HLF8QUE7VV6T", Request id "0HLF8QUE7VV6T:00000004": the application completed without reading the entire request body.
  • Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "Authenticate", controller = "Account", page = ""}. Executing action WebApp.Controllers.AccountController.Authenticate (WebApp)
  • 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\2.1.1\\System.Runtime.Serialization.Primitives.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
  • 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\\Program Files\\dotnet\\shared\\Microsoft.NETCore.App\\2.1.1\\System.Data.Common.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
  • Microsoft.AspNetCore.Mvc.Infrastructure.ObjectResultExecutor:Information: Executing ObjectResult, writing value of type 'Microsoft.AspNetCore.Mvc.SerializableError'.
  • Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action WebApp.Controllers.AccountController.Authenticate (WebApp) in 78.8614ms
  • Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 96.9303ms 400 application/json; charset=utf-8

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM