Custom 404 errors using Global.asax file not alway

2019-08-05 09:23发布

We currently use the config file to throw the 404 error page, however we would like to move this to the Global.asax file as we want to be able to use multiple 404 error pages, depending on where the user is on the page.

Our current setup:

<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
</customErrors>

<httpErrors existingResponse="Replace" defaultResponseMode="Redirect" errorMode="Custom">
    <remove statusCode="404"/>
    <error statusCode="404" responseMode="Redirect" path="/PageNotFound.aspx"/>
</httpErrors>

We have added the statusCode check in the Application_Error in the Global.asax file.

if (statusCode == 404)
{
    Response.Redirect(String.Format("/PageNotFound.aspx"));
}

However when removing the HttpErrors from the config file, the Application Error is not called, unless we specifically throw a 404 error code in the page. Like our news section, if the news article doesn't exists, we throw the 404 error page, and it goes to the correct error page (ie. http://[website].com/article?article=blah - This article does not exists).

I've tried various things, however it always shows the IIS 404 error page, and the not the custom one when just typing in the wrong page name (ie. http://[website].com/blah - This page does not exists) . Trying to debug it, the breakpoint in the Application_Error in the Global.asax file is never hit.

We need to get the Application_Errors working so that it is also called when you go to a page that does not exists.

1条回答
疯言疯语
2楼-- · 2019-08-05 10:05

Take a look at this: https://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.140%29.aspx#robustProgrammingToggle

It basically says that if it is non-existent page it will not catch it. You will have to create a custom handler in IIS. So I think that explains why it is not stepping into the Application_Error method.

Setting up a custom error handler in IIS: https://technet.microsoft.com/en-us/library/cc753103%28v=ws.10%29.aspx

查看更多
登录 后发表回答