How do I stop IIS7 from putting out its own 404 before my MVC app gets a chance to handle it?

半世苍凉 提交于 2019-12-18 15:02:52

问题


I have an ASP.NET MVC 2 application, which has an Application_Error event handler in global.asax. In this, I'm detecting the case where the Exception type is HttpException and the HTTP code is 404, and redirecting to my own 404-handling page.

This works fine on my Cassini development server, but now I'm trying to move it over to my production server which has IIS7 (using integrated mode).

When I request a non-existent URL, IIS7 is showing its own 404 page, and so far as I can tell, my Application_Error method is never called.

How do I fix that?


回答1:


I answered that in another post: ASP.NET Application hosted on IIS7 that is ignoring custom errors and falls back to IIS errors

"To disable the IIS error messages you have to set

  Response.TrySkipIisCustomErrors = true;

in your error page. After that, your Error messages should show without problem."




回答2:


Can't you just turn off the 404 httpError:

    <httpErrors errorMode="Custom">
        <remove statusCode="404" subStatusCode="-1" />
    </httpErrors>



回答3:


In ASP.NET MVC I use a custom ErrorController with an Index method (default handler) and a few custom handlers (401, 404) using the following web.config settings

<!--  CUSTOM ERROR MESSAGES
Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable. 
Add <error> tags for each of the errors you want to handle.   
"On" Always display custom (friendly) messages.
"Off" Always display detailed ASP.NET error information.
"RemoteOnly" Display custom (friendly) messages only to users not running 
on the local Web server. This setting is recommended for security purposes, so 
that you do not display application detail information to remote clients. -->
<customErrors mode="Off" defaultRedirect="~/Error">
    <error statusCode="401" redirect="~/Error/Unauthorized" />
    <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

I don't use Application_Error except for logging purposes.




回答4:


This is discussed in the MVC overview tutorials. It is probably the the case that your IIS 7 is set up in Classic mode. See:

Using ASP.NET MVC with Different Versions of IIS (C#)




回答5:


The Answer by Flynn solved my issue of ASP.NET taking control of the 404

Now I am able to do this:

Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 404;
Response.Write("<script type='text/javascript'>setTimeout(function () { window.location = '/'; }, 1000)</script>");
HttpContext.Current.ApplicationInstance.CompleteRequest();


来源:https://stackoverflow.com/questions/2631675/how-do-i-stop-iis7-from-putting-out-its-own-404-before-my-mvc-app-gets-a-chance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!