No1Lives4Ever
No1Lives4Ever

Reputation: 6903

ASP.NET CORE: Custom validation

Background

I have a web api that written with asp.net core v2.1. This is the function which exposed by my service:

[HttpPost]
[Route("submit")]
public async Task<ActionResult<int>> DoIt(CustomModel model)
{
    if (!ModelState.IsValid)
        return new StatusCodeResult(403); // Custom 403 will be here.

    // ...
}

And this is the CustomModel:

public class CustomModel
{
    [Required]
    public int MagicNumber { get; set; }
}

This combination (method+model) is working fine until the client don't provide the MagicNumber to the server.

The Problem

In contrast to the old asp.net (.net framework), when model validation is failed - an automatic 403 error message is sent to the client.

I want to prevent this default behavior and give a custom error message to the user. I prefer to define a custom response like this way:

[HttpPost]
[Route("submit")]
public async Task<ActionResult<int>> Submit(CustomModel model)
{
    if (!ModelState.IsValid)
        return new CustomErrorCode_BadRequest();
    //...
}

Things I tried

The only way that I could prevent the automatic "bad-request" response is by adding this code to the Startup.cs file

services.AddMvc(options => options.ModelValidatorProviders.Clear());

After adding this line of code, I was able to reach my if (!ModelState.IsValid) statement. Before that, the request was blocked on earlier step. Unfortenetly, the ModelState.IsValid return always true (no matter what is the input). I guess that this is because I "cleared" all of the validators - which sounds like a bad idea.

How it should be done?

Thanks!

Upvotes: 2

Views: 1376

Answers (1)

No1Lives4Ever
No1Lives4Ever

Reputation: 6903

Thanks for @Compufreak (source: https://stackoverflow.com/a/51522487/3085985) Adding this code to Starup.cs solved the problem:

    services.Configure<ApiBehaviorOptions>(opt =>
    {
        opt.SuppressModelStateInvalidFilter = true;
    });

Upvotes: 1

Related Questions