ASP.NET MVC 3中返回404错误

30

我尝试了以下两种方法来使页面返回404错误:

public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}

但两者都只渲染空白页面。我该如何在ASP.NET MVC 3中手动返回404错误?

5个回答

63
如果您使用Fiddler检查响应,我相信您会发现空白页面实际上返回了404状态码。问题在于没有呈现任何视图,因此出现了空白页面。 您可以通过将customErrors元素添加到web.config中来显示实际视图,当特定状态代码发生时,它将重定向用户到特定的url,然后您可以像处理任何url一样处理它。以下是详细步骤: 首先,在适当的位置抛出HttpException。在实例化异常时,请确保使用一个带有http状态代码参数的重载,如下所示。
throw new HttpException(404, "NotFound");

然后在您的web.config文件中添加一个自定义错误处理程序,以便您确定在发生上述异常时应呈现哪个视图。以下是一个示例:

<configuration>
    <system.web>
        <customErrors mode="On">
          <error statusCode="404" redirect="~/404"/>
        </customErrors>
    </system.web>
</configuration>

现在在你的Global.asax中添加一个路由条目,它将处理url "404",并将请求传递给控制器的操作,该操作将显示你的404页面的视图。

Global.asax

routes.MapRoute(
    "404", 
    "404", 
    new { controller = "Commons", action = "HttpStatus404" }
);

CommonsController

public ActionResult HttpStatus404()
{
    return View();
}

所有剩下的工作就是为上面的操作添加一个视图。
以上方法有一个注意事项:根据书籍“Pro ASP.NET 4 in C# 2010”(Apress)的说法,如果您使用的是IIS 7,则customErrors的使用已过时。相反,您应该使用httpErrors部分。以下是该书的引用:

这对我有效,但是我不得不在控制器函数中添加Response.StatusCode = 404;以避免返回404页面和200状态码。 - gregtheross

17

我成功地使用了这个:

return new HttpNotFoundResult();

15

6
你应该使用 标签。
// returns 404 Not Found as EmptyResult() which is suitable for ajax calls
return new HttpNotFoundResult();

当您通过AJAX调用您的控制器并且没有找到任何内容时:

当您通过经典方式调用控制器操作并返回视图时,您应该使用:

// throwing new exception returns 404 and redirects to the view defined in web.config <customErrors> section
throw new HttpException(404, ExceptionMessages.Error_404_ContentNotFound);

2
您可以通过个性化设置来定制404错误页面的显示效果。
return new HttpStatusCodeResult(404, "My message");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接