IIS overriding custom 404 error page in ASP.NET

2019-04-12 09:54发布

问题:

I am trying to create a 404 error page and currently I have all of the following/tried all of the following to try and accomplish this. When the user types in :

http://name/something.aspx

It works just as its supposed to. But if the user types in:

http://name/NotAFile

with no .aspx then IIS7 takes matters into its own hands and I get the lovely error page that IIS7 comes with. The goal is that the site redirects with only a 404 status code (so not a 200, or a 302 redirect). I have tried in both the web config with:

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

This works for the url with a .aspx file extension but not for no extension. Same with this approach in the global.asax

void Application_Error(object sender, EventArgs e)
{
    var serverError = Server.GetLastError() as HttpException;

    if (serverError != null)
    {
        if (serverError.GetHttpCode() == 404)
        {
            Server.ClearError();
            Server.Transfer("~/error/NotFound.aspx");
        }

        Server.Transfer("~/error/Default.aspx");
    }
}

The same results are present for this :( My final attempt was to apply this to the web config:

<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>

With this I just get a plain white screen with nothing on it... Any thoughts or comments would be greatly appreciated!! Thanks in advance!

回答1:

It seems that your application is running in classic pipeline mode. Change it to integrated and your problem will be fixed. Here is an article about pipeline modes and their differences - http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-7-integrated-pipeline/



回答2:

The following codes works with both .aspx and other file types:

Global.asax

void Application_Error(object sender, EventArgs e)
{
    var serverError = Server.GetLastError() as HttpException;
    if (serverError != null)
    {
        if (serverError.GetHttpCode() == 404)
        {
            Server.ClearError();
            Response.Redirect("~/NotFound.aspx?URL=" + Request.Url.ToString());
        }
        Response.Redirect("~/Default.aspx");
    }
}

Web.config

<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>


回答3:

For classic asp you can use this

<system.webServer>
    <httpErrors>
      <clear />
      <error statusCode="404" subStatusCode="-1" path="/404.html" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>


回答4:

<system.webServer >
    <httpErrors errorMode="Custom">
      <remove statusCode="404" subStatusCode="-1" />
       <error statusCode="404" path="http://www.seair.co.in/Page-not-found.aspx" responseMode="Redirect" />
    </httpErrors>
</system.webServer>

use the code in your config and give complete path of error page