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.
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.
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.
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
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
精彩评论