'.NET core can you set a custom error for HTTP 415?

I've been trying to figure this one out and for the life of me I cannot get it to work.

Is there a way to intercept, with middlewares or the like, the request checking that .NET core web APIs does? Most specifically the the ones that result in the "415 Unsupported Media Type" exceptions.

Google just gives me the good ol' "just set your media type on your request" answers

Edit: for clarity I want this so I can have all my errors in the same format no matter what goes wrong, even things in code that is not my own.



Solution 1:[1]

In your startup class you can configure where the middleware points to for your error handling.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler("/Home/Error");
}

And then in your home controller.

[AllowAnonymous]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[HttpPost]
public async Task<IActionResult> Error()
{
    var model = new ErrorViewModel
    {
        RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
    };

    var context = HttpContext.Features.Get<IExceptionHandlerFeature>();

    var exceptionHandlerPathFeature =
    HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    model.ExceptionMessage = exceptionHandlerPathFeature?.Error.Message;
    model.Path = exceptionHandlerPathFeature?.Path;

    _logger.LogError(model.ExceptionMessage);

    return View(model);
}

This will output the error message to the default error page. You don't want to do this in production but this gives you the idea of how you can handle generic errors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 averybusinesssolutions