【问题标题】:404 Custom Redirect404自定义重定向
【发布时间】:2011-11-30 22:09:55
【问题描述】:

您好,如果响应是 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)

【问题讨论】:

  • 你的意思是把Response.Redirect(notFound );
  • 啊,发帖时打错字了,但还是有问题。谢谢
  • 你能试试吗(Response.Status == 404)(我不确定它会起作用,但试试看)
  • 试过了.. 仍然没有找到它,它是 (Response.StatusCode == 404) 因为 (Response.Status == "expects a string") 并且也尝试过 (Resonse.Status == "404") 并尝试过 (Response.Status == "404 not found") 都不起作用
  • (Response.status == HttpStatusCode.NotFound)

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


【解决方案1】:

您还可以使用 web.config 自定义错误部分 - as shown here

例如在 system.web 部分,

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      你可以添加到你的 web.config 来做这个重定向,你不需要使用 Application_BeginRequest 来处理这个。

      看到这个ServerFault question

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

      进一步研究,在 HttpWebResponse 类中使用了一个 HttpStatusCode。因此,使用应用程序的不同覆盖来获取默认响应,然后根据枚举检查它的状态可能是有意义的。

      【讨论】:

      • 无论如何,出于某种原因,他们希望在 asax 中完成,这将是在那里完成的方式?
      【解决方案4】:

      你也可以使用 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-18
        • 1970-01-01
        • 2018-03-20
        • 2015-08-01
        • 2016-11-21
        • 2012-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多