404自定义重定向

时间:2011-10-04 18:16:55

标签: c# asp.net redirect http-status-code-404

您好我正在尝试重定向,如果响应是404,但它没有按预期工作,您可以专家看到问题吗?它仍然是通用的404

在我的Global.asax

protected void Application_BeginRequest(Object sender, EventArgs e)
{
       if (Response.Status == "404 Not Found")
        {
            string notFound = "~/custom_notfound.aspx";
            Response.Redirect(notFound);
        } 

}

更新

到目前为止已经尝试了

(Response.Status == "404 Not Found")
(Response.Status == "404")
(Response.StatusCode == 404)

4 个答案:

答案 0 :(得分:8)

您还可以使用web.config customerrors部分 - as shown here

e.g。在system.web部分中,

<customErrors mode="On" defaultRedirect="/custom_error.aspx">
    <error statusCode="404" redirect="/custom_notfound.aspx" />
</customErrors>

答案 1 :(得分:3)

我认为BeginRequest不会知道404错误。尝试实现Application_Error。检查Server.GetLastError()是否是HttpException,如果是,请检查状态。

答案 2 :(得分:2)

您可以添加到web.config进行此重定向,您无需使用Application_BeginRequest来处理此问题。

请参阅此ServerFault question

如果您不能使用web.config,那么我会将您的启动页面设置为不存在的页面,在BeginRequest中放置一个断点,调试应用程序并查看请求以查看如何确定它是404.这将更容易确定最佳解决方案。

再看一下,HttpWebResponse类中使用了HttpStatusCode。因此,使用Application的不同覆盖来获取默认响应,然后根据Enum检查它的状态可能是有意义的。

答案 3 :(得分:0)

您也可以使用web.config

<system.webServer>
  <httpErrors errorMode="Custom" defaultResponseMode="File" >
     <remove statusCode="404" />
     <remove statusCode="500" />
     <error statusCode="404" path="404.html" />
     <error statusCode="500" path="500.html" />
   </httpErrors>
</system.webServer>
相关问题