我尝试了以下两种方法来使页面返回404错误:
public ActionResult Index()
{
return new HttpStatusCodeResult(404);
}
public ActionResult NotFound()
{
return HttpNotFound();
}
但两者都只渲染空白页面。我该如何在ASP.NET MVC 3中手动返回404错误?
我尝试了以下两种方法来使页面返回404错误:
public ActionResult Index()
{
return new HttpStatusCodeResult(404);
}
public ActionResult NotFound()
{
return HttpNotFound();
}
但两者都只渲染空白页面。我该如何在ASP.NET MVC 3中手动返回404错误?
throw new HttpException(404, "NotFound");
然后在您的web.config文件中添加一个自定义错误处理程序,以便您确定在发生上述异常时应呈现哪个视图。以下是一个示例:
<configuration>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/404"/>
</customErrors>
</system.web>
</configuration>
Global.asax
routes.MapRoute(
"404",
"404",
new { controller = "Commons", action = "HttpStatus404" }
);
CommonsController
public ActionResult HttpStatus404()
{
return View();
}
我成功地使用了这个:
return new HttpNotFoundResult();
标签。// 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);
return new HttpStatusCodeResult(404, "My message");
Response.StatusCode = 404;
以避免返回404页面和200状态码。 - gregtheross