使用asp.net MVC以编程方式重定向到404页面

时间:2012-05-22 13:05:37

标签: asp.net-mvc http-status-code-404

我创建了一个Asp.net MVC应用程序。现在需要404处理。

更新了global.asax并根据状态代码显示404页面。还在web.config中添加了customErrors属性。工作正常。

现在,当任何不符合我们要求的内容时,我想以编程方式重定向到404。

即。

if(!valid) 
{
    return RedirectToAction("Index", "Page404");
}

它工作正常,但有2个状态,一个是301&然后是404.那我怎么能阻止301呢?我只需要404。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:41)

只需从您的行动中退回:

return HttpNotFound();

答案 1 :(得分:3)

web.config中,添加:

<customErrors mode="On" >
       <error statusCode="404" redirect="/404.shtml" />
</customErrors>

当找不到请求的资源时,这将在404.shtml页面上重定向。

注意:无需以编程方式重定向用户以解决此类情况。


修改 我确实建议:

if (Context.Response.StatusCode == 404) {
  // handle this
}

答案 2 :(得分:2)

只需在状态代码中删除404:

Response.StatusCode = (int)System.Net.HttpStatusCode.NotFound