404 Redirecting for non aspx pages

2019-01-12 03:33发布

问题:

I am using the web.config code below to redirect requests to missing pages to a 404 error handling page:

<customErrors mode="On" defaultRedirect="404.aspx" redirectMode="ResponseRewrite">
  <error statusCode="404" redirect="404.aspx"/>
</customErrors>

It works fine when I look for pages such as "missing.aspx" but it does not work for pages without the ".aspx" extension such as "missing.asp" or just "missing". When it does not work, it just loads a standard IIS 7.5 error page.

What am I doing wrong? I am using .net 4. I noticed other people asking the same question but they didn't get an answer.

Thanks!

回答1:

As dbaseman states this is because the asp.net handlers are not called for non-asp.net files. An easy way to force the asp.net handler to operate on all requests is to set the following in your web.config.

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
</system.webServer>

This tells IIS to run through all of the managed modules for all requests such as .html, .jpg, .css, .js, etc. This is typically frowned upon as it just introduces extra processing and latency.

http://www.hanselman.com/blog/BackToBasicsDynamicImageGenerationASPNETControllersRoutingIHttpHandlersAndRunAllManagedModulesForAllRequests.aspx

Another option to try (cleaner than the above) was posted as an answer here: https://stackoverflow.com/a/6661699/701062



回答2:

The reason is that non-ASPX extensions never make it to the ASP.NET handler; those errors you see are coming from IIS. There is a separate section httpErrors under system.webServer in web.config that you will need to configure to handle these errors. See here for more info.

Example from the link:

<configuration>
   <system.webServer>
      <httpErrors errorMode="DetailedLocalOnly" defaultResponseMode="File" >
         <remove statusCode="500" />
         <error statusCode="500"
            prefixLanguageFilePath="C:\Contoso\Content\errors"
            path="500.htm" />
       </httpErrors>
   </system.webServer>
</configuration>