Custom Error Handler for Http Error 405 in MVC

2019-08-02 12:00发布

问题:

I can't seem to figure out how to custom handle this error. I have a endpoint defined like this:

[HttpGet] public ActionResult Test() { ... }

If I try to POST to this endpoint it throws the http 405 error which is correct. The problem is I want to provide a custom error page and not the IIS default one. I've tried breaking in the application_error method in global.asax but it never get's called, and I've tried adding the <customErrors /> section in web.config but to no avail.

Any suggestions?

回答1:

Are you using MVC3? If so, watch out for

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
  filters.Add(new HandleErrorAttribute());
}

in your global.asax.

This filter will catch any exception thrown in a controller and make it a 500 response code. It will then try and find a View called "Error". Comment this out and customErrors will work as you expect.

Also, double check for [HandleError] attributes on the action method or controller you are using.