简体   繁体   中英

Definitive Guide to Handling 500 Errors in IIS6, IIS7, ASP.NET MVC3 with Custom Page

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?

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".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM