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

use*_*362 20 .net c# asp.net-mvc

我如何实现以下功能?

我的控制器:

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

  //return the view with 200 http header
  return View();
Run Code Online (Sandbox Code Playgroud)

fer*_*ero 32

写吧

Response.StatusCode = 404;
Run Code Online (Sandbox Code Playgroud)

在返回视图之前.

  • 这正是`返回HttpNotFound();`的内容.它为当前的HttpContext响应添加了404 StatusCode和StatusDescription. (5认同)

dsg*_*fin 15

if (something == null)
{         
   return new HttpNotFoundResult(); // 404
}
else
{
   return new HttpStatusCodeResult(HttpStatusCode.OK); // 200
}
Run Code Online (Sandbox Code Playgroud)

  • 问题不是如何返回404,而是如何返回带有404 http header的同一页面。 (2认同)
  • 如果您考虑一下,对Web服务器的每个请求都只返回一个带有状态代码的响应.如果状态代码是200,那么通常会有一些我们认为是页面的html,但就服务器而言,它只是一个状态代码,无论是200,404等. (2认同)

Ala*_*Low 8

if (something == null)
{         
    Response.StatusCode = (int)HttpStatusCode.NotFound;
    return View();          
}

//return the view with 200 http header
return View();
Run Code Online (Sandbox Code Playgroud)


Med*_*kal 5

您应该将TrySkipIisCustomErrors属性设置Responsetrue.

public ActionResult NotFound()
{
    Response.StatusCode = 404;
    Response.TrySkipIisCustomErrors = true;
    return View();
}
Run Code Online (Sandbox Code Playgroud)

  • 我的场景的最佳答案,因为它允许您返回任意视图而不是服务器接管并显示默认的 404 响应 (2认同)