如何使用asp.net mvc视图返回404

我如何实现以下function?

我的控制器

if (something == null) { //return the view with 404 http header return View(); } //return the view with 200 http header return View(); 

写吧

 Response.StatusCode = 404; 

在返回视图之前。

 if (something == null) { return new HttpNotFoundResult(); // 404 } else { return new HttpStatusCodeResult(HttpStatusCode.OK); // 200 } 
 if (something == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } //return the view with 200 http header return View(); 

您应该将Response TrySkipIisCustomErrors属性设置为true

 public ActionResult NotFound() { Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; return View(); } 
 if (something == null) { return HttpNotFound(); } return View(); 

我会抛出404exception并创建一个自定义exceptionfilter,返回404错误的未找到页面。 内置的HandleErrorfilter不处理404错误。

 if (something == null) { throw new HttpException(404, "Not found") } return View();