Answers:
有多种方法可以做到
throw new HttpException(404, "Some description");
在ASP.NET MVC 3和更高版本中,您可以从控制器返回HttpNotFoundResult。
return new HttpNotFoundResult("optional description");
return new HttpNotFoundResult("optional description");
HttpNotFound()
。因此,您可以返回return HttpNotFound("optional description")
。
代码:
if (id == null)
{
throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}
Web.config
<customErrors mode="On">
<error statusCode="404" redirect="/Home/NotFound" />
</customErrors>
我用了这个:
Response.StatusCode = 404;
return null;
在NerdDinner中。尝试它
public ActionResult Details(int? id) {
if (id == null) {
return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
}
...
}
在我添加以下中间行之前,以上示例均不适用于我:
public ActionResult FourOhFour()
{
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true; // this line made it work
return View();
}
return HttpNotFound();
对您不起作用吗?您的系统多大了?
return HttpNotFound();
吗?对于MVC 4或更高版本,它可以正常工作。msdn.microsoft.com/zh-cn/library/… “仅当您的应用程序托管在IIS 7.0中时,才使用TrySkipIisCustomErrors属性。在IIS 7.0中以经典模式运行时,TrySkipIisCustomErrors属性的默认值为true。在集成模式下运行,TrySkipIisCustomErrors属性的默认值为false。”
在.NET Core 1.1中:
return new NotFoundObjectResult(null);
您也可以这样做:
if (response.Data.IsPresent == false)
{
return StatusCode(HttpStatusCode.NoContent);
}