在仍显示页面时设置404响应

时间:2012-09-25 12:01:49

标签: c# asp.net http

我有产品的详细信息页面。产品是通过查询字符串中的id获取的,如果在数据库中找到具有id的产品,我们会显示详细信息,否则我们会显示“此项无法找到”消息。很标准的东西。我想要做的是显示详细信息页面,其中包含“此商品无法找到”消息,但会发送404回复。这样Google就会取消已删除的商品的索引。

所以我有类似的东西(简化):

<asp:Panel ID="pnlDetails" runat="server" Visible="false">
    item details go here
</asp:Panel>

<asp:Panel ID="pnlError" runat="server" Visible="false">
    <p>The specified  item could not be found.</p>
</asp:Panel>

And in the code behind:

if(itemFound)
{
   showDetails();
}
else
{
   showError();
}

private void showDetails()
{
   pnlDetails.Visible = true; 
   //fill in details
}

private void showError()
{
    //set response
    Response.StatusCode = 404;
    pnlError.Visible = true;
}

现在发生的事情是我看到错误面板但我仍然得到200响应。谁能告诉我我做错了什么?非常感谢任何建议!

编辑:我在Page_Load事件处理程序中调用这些方法。

3 个答案:

答案 0 :(得分:2)

我明白了......因为你的代码不会抛出404,你实际上也想要它,所以谷歌会自然地清理你的死链接......试试这个:stackoverflow.throwing404errorsForMissingParameters

另外,这很有用(靠近底部)forums.asp.net/throwing404InHTTPResponse。例如,HttpContext.Current.Respone.StatusCode = 404;

protected void Page_Load(object sender, EventArgs e) 
{ 
    Response.StatusCode = 404; 
    Response.End(); 
}

答案 1 :(得分:1)

谷歌说......

  

如果您网站上的过期网页出现在搜索结果中,请确保   页面返回状态404(未找到)或410(已消失)   在标题中。

Here is the source
那么你可以做什么..

  1. 找不到该项目 - 重定向到您的自定义404页面。
  2. 在404页面的Page_Load事件中添加此内容..

    Response.StatusCode = 404;

  3. 但是,只需执行此操作即可返回HTTP 302 Redirect代码,然后返回HTTP 200 - ok代码。因此,该页面不会从Google的索引中删除 3.打开Global.asax文件(如果不存在,请添加它)。添加以下代码以处理404(未找到页面)错误

         protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        if (ex is HttpException)
        {
            if (((HttpException)(ex)).GetHttpCode() == 404)
                Server.Transfer("~/404.aspx");
        }
        Server.Transfer("~/AnyOtherError.aspx");
    }
    

    但是在这种情况下,请确保在web.config中没有针对404的customErrors配置。希望它有所帮助。

答案 2 :(得分:1)

Render方法中设置状态代码,因此它可能如下所示:

protected override void Render(HtmlTextWriter writer) 
{ 
    base.Render(writer); 
    Response.StatusCode = 404; 
    pnlError.Visible = true;
}