Definitive Guide to Handling 500 Errors in IIS6, I

2019-04-01 21:11发布

问题:

I'm trying to add a 500 error handling page to my ASP.NET MVC3 project.

I want my custom error page displayed regardless of local or remote access. My website is running on IIS6,IIS7 & IIS7.5 Express

I want it displayed when:

  • An exception is thrown in Application_BeginRequest
  • An exception is thrown in Application_Error
  • An exception is thrown in a static constructor in the Website Project
  • An exception is thrown in a Controller
  • An exception is thrown in a view
  • An exception thrown anywhere pretty much.

I haven't been able to do in this, in fact I haven't been able to get any custom error pages to display at all.

My error page lives in ~/Views/Shared/Error.aspx

My Application_Error method in Global.asax.cs just logs the thrown exception.

My web.config has this:

<customErrors mode="On" defaultRedirect="~/Views/Shared/Error.aspx" redirectMode="ResponseRewrite">
</customErrors>
...
<system.webServer>
  <httpErrors errorMode="Custom" />
  ...
</system.webServer>

What am I missing? What do I need to do to handle these scenarios?

回答1:

For IIS 7+, you're only missing the part that defines which httpErrors to handle with custom handlers:

<configuration>
   <system.webServer>
      <httpErrors errorMode="Custom">
         <remove statusCode="500" />
         <error statusCode="500" path="~/Views/Shared/Error.aspx" />
       </httpErrors>
   </system.webServer>
</configuration>

(The <remove /> tag is optional, depending on your web.config hierarchy.)

For IIS 6 and below, You have to set this via the IIS Manager by going to the appropriate Properties page, Custom Errors tab, then edit the appropriate HTTPError line to "Message type:" "URL" and "URL:" "~/Views/Shared/Error.aspx".



回答2:

The best approach is to find out why your BeginRequest is throwing an exception in the first place. This should not be happening. In Application_Error, one alternative is to use GetBaseException and then just redirect to your custom error page with the exception information.