Chris
Chris

Reputation: 27384

Conditionally override all routes (MVC / ASP)

I have an ASP.NET MVC website that connects to a DB via a Web Service.

If the WebService is not contactable, I want to redirect the user to a page explaining the service isn't running. Currently it just crashes when the WebService doesnt respond properly.

What is the best method to achieve this? I have lots of controllers so writing error trapping code for each function in each controller for this specific case would be tedious and involve a lot of code repeation.

Upvotes: 0

Views: 353

Answers (4)

Chris
Chris

Reputation: 27384

Found a great tutorial here on it. Implemented it and it all works as expected on a global level. Great!

Update: Actually that only helped with 404's and didnt handle them properly. I managed to find another question here on stackoverflow that answers it perfectly - find the link here

Upvotes: 1

swapneel
swapneel

Reputation: 3061

You need to have a base controllor and override OnException protected override void OnException(ExceptionContext filterContext) i.e will be Catch block for all exceptions in Controller Actions

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062925

One easy option is to write a base-controller; override the methods you want (whether that is before the call (OnActionExecuting) or upon exception (OnException)), and just add : MyBaseController to each controller.

Another option would be to decorate each controller with a filter-attribute that does the same work.

Upvotes: 1

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68687

You can use the HandleError attribute on the controller to catch the specific exceptions and redirect to an error page. You can also inherit from it and override the OnException method with custom logic.

Upvotes: 1

Related Questions