noor
noor

Reputation: 122

How to throw custom errors on some routes in c#

I get custom error if I do something like

https://localhost:xxxx/TryStuff  

but if I do something like

https://localhost:xxxx/AbcController/Details/1234/TryStuff

it doesn't throw a custom error. It throws something like

enter image description here

Route file:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);


routes.MapRoute(
    name: "Error",
    url: "{controller}/{action}/{id}",
    defaults: new
    {
        controller = "Error",
        action = "NotFound",
        id = UrlParameter.Optional
    });

Upvotes: 1

Views: 252

Answers (1)

Nkosi
Nkosi

Reputation: 247018

You need a catch all route

//Catch-All InValid (NotFound) Routes
routes.MapRoute(
    name: "NotFound",
    url: "{*url}",
    defaults: new { controller = "Error", action = "NotFound" }
);

Add this route after all other routes.

Any routes that are not caught before will match this one and route to the appropriate controller.

Upvotes: 2

Related Questions