404 page response.redirect vs server.transfer

5 asp.net http-status-code-404

当在ASP.NET中处理404错误时,可以设置404错误以重定向到将404响应代码发送到浏览器的页面,或者应该使用server.transfer,以便在URL保留时将404标头发送到浏览器相同?

Ted*_*Ted 3

customErrors statusCode="404" 会导致 302 临时重定向,然后是 404(如果您已在 404 页面代码中进行了设置)。

因此,以下内容应该在您的 global.asax 或错误 HttpModule 中为您完成:

    protected void Application_Error(Object sender, EventArgs e)
    {
        Exception exception = Server.GetLastError();
        if (exception is HttpUnhandledException)
        {
            if (exception.InnerException == null)
            {
                Server.Transfer(ERROR_PAGE_LOCATION, false);
                return;
            }
            exception = exception.InnerException;
        }

        if (exception is HttpException)
        {
            if (((HttpException)exception).GetHttpCode() == 404)
            {
                Server.ClearError();
                Server.Transfer(NOT_FOUND_PAGE_LOCATION);
                return;
            }
        }

        if (Context != null && Context.IsCustomErrorEnabled)
            Server.Transfer(ERROR_PAGE_LOCATION, false);
        else
            Log.Error("Unhandled exception trapped in Global.asax", exception);
    }
Run Code Online (Sandbox Code Playgroud)

编辑:哦,在 ASP.NET 中实现 404 的最佳方法让我走上了命令式的 Server.ClearError(); 之路。

请参阅http://www.andornot.com/blog/post/Handling-404-errors-with-ASPNET.aspx我发表的一篇文章涵盖了所有这些内容。