2

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!

8

1 Answer 1

1

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;
    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.