How do I customize ASP.Net Core model binding errors?
Asked Answered
P

1

24

I would like to return only standardized error responses from my Web API (Asp.net Core 2.1), but I can't seem to figure out how to handle model binding errors.

The project is just created from the "ASP.NET Core Web Application" > "API" template. I've got a simple action defined as:

[Route("[controller]")]
[ApiController]
public class MyTestController : ControllerBase
{
    [HttpGet("{id}")]
    public ActionResult<TestModel> Get(Guid id)
    {
        return new TestModel() { Greeting = "Hello World!" };
    }
}

public class TestModel
{
    public string Greeting { get; set; }
}

If I make a request to this action with an invalid Guid (eg, https://localhost:44303/MyTest/asdf), I get back the following response:

{
    "id": [
        "The value 'asdf' is not valid."
    ]
}

I've got the following code in Startup.Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    JsonErrorMiddleware.CreateSingleton(env);

    if (!env.IsDevelopment())
    {
        app.UseHsts();
    }

    app
        .UseHttpsRedirection()
        .UseStatusCodePages(async ctx => { await JsonErrorMiddleware.Instance.Invoke(ctx.HttpContext); })
        .UseExceptionHandler(new ExceptionHandlerOptions() { ExceptionHandler = JsonErrorMiddleware.Instance.Invoke })
        .UseMvc()
}

JsonErrorMiddleware is simply a class that converts errors to the correct shape I want to return and puts them into the response. It is not getting called at all for the model binding errors (no Exception is thrown and UseStatusCodePages is not called).

How do I hook into the model binding to provide a standardized error response across all actions in my project?

I've read a bunch of articles, but they all seem to either discuss global exception handling or validation errors.

Phanerogam answered 3/7, 2018 at 0:39 Comment(0)
L
69

It's worth mentioning that ASP.NET Core 2.1 added the [ApiController] attribute, which among other things, automatically handles model validation errors by returning a BadRequestObjectResult with ModelState passed in. In other words, if you decorate your controllers with that attribute, you no longer need to do the if (!ModelState.IsValid) check.

Additionally, the functionality is also extensible. In Startup, you can add:

services.Configure<ApiBehaviorOptions>(o =>
{
    o.InvalidModelStateResponseFactory = actionContext =>
        new BadRequestObjectResult(actionContext.ModelState);
});

The above is just what already happens by default, but you can customize the lambda that InvalidModelStateResponseFactory is set to in order to return whatever you like.

Lineage answered 3/7, 2018 at 17:5 Comment(4)
For completeness - the ApiBehaviorOptions will work on controllers only with ApiController attribute decorated! That also means that Route attribue on the controller itself has to be also provided and also the way how binding is done will change also. Details provided in the link here: #45941746Levinson
ApiController attribute is what has helped meArdie
Will have only effect if you use PostConfigure instead of Configure (as of ASP.NET Core 3.1.8)Dipteral
@g.pickardou, Thanks, relevant in my case.Embank

© 2022 - 2024 — McMap. All rights reserved.