mko
mko

Reputation: 7325

Asp.net core web api custom error response for unmatched controller action?

I have an issue with ASP.NET Core Web API, where I want to display a custom error message model if non of the controller actions were matched.

So, it would be a 404 error but with a customized body.

I haven't tried anything because I am not sure if this is even possible.

Upvotes: 0

Views: 481

Answers (2)

Mohsen Esmailpour
Mohsen Esmailpour

Reputation: 11544

You can add a catch-all route by adding an action method with a route that will always match if no other does.

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");

    routes.MapRoute(
        name: "CatchAll",
        template: "{*url}",
        defaults: new { controller = "CatchAll", action = "Index" });
});

For Web API:

public class CatchAllController : Controller
{
    [HttpGet("{*url}", Order = int.MaxValue)]
    public IActionResult Index()
    {
        return NotFound(YourModel)
    }
}

For MVC:

public class CatchAllController : Controller
{
    public IActionResult Index()
    {
        Response.StatusCode = StatusCodes.Status404NotFound;
        return View();
    }
}

Upvotes: 2

A_kat
A_kat

Reputation: 1537

   app.UseExceptionHandler(errorApp =>
   {
      errorApp.Run(async context =>
      {
        context.Response.StatusCode = 500;
      });
   });

Using this middleware you can actually catch the code and then handle it accordingly. It's taken from this page . There are various other examples in the link some simpler ones might fit you better

Upvotes: 0

Related Questions