Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 != "[email protected]" || 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"}
like image 977
Maksym Lapshyn Avatar asked Jul 13 '18 16:07

Maksym Lapshyn


People also ask

What is model validation in ASP NET Core?

Model Validation in ASP.NET Core from Beginning to Expert. Model Validation is a process to ensure the data received from the View is appropriate to bind the Model. If it is not, then appropriate error messages are displayed on the View, and that will help user to rectify the problem.

How to display all validation errors in one place using CSS?

This span can be styled with any CSS. It is internally used by ASP.NET Core for displaying validation errors. Additionally, you can add an empty tag (say, a div) to show all the validation errors together at one place. For this the attribute asp-validation-summary="All" must be set as shown.

Is ASP NET Core 2 2 out of support?

While we attempt to avoid such incompatibilities, ASP.NET Core 2.2 has been out of support for some time now so it’s difficult for us to capture these kinds of regressions. We would strongly encourage targeting a supported version of ASP.NET Core to ensure continued support.

What is server side validation?

Server side validation is a pre-check of the POSTED form data before it is processed and passed to a database. Even though client-side validation is sufficient in most cases, yet a second check may be needed on the server side for a confirmed assurance of the sanctity of data that is about to be passed to a database.


1 Answers

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

    ...
}
like image 182
spottedmahn Avatar answered Sep 20 '22 19:09

spottedmahn