0

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.

2 Answers 2

2

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

Comments

0
   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

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.