如果实体对象为null,则自动从操作方法中抛出404异常 [英] Automatically throw 404 exception from action method if entity object is null
问题描述
例如,我们有简单的操作方法来显示任何具有正确ID的书:
For example, we have simple action method to show any book with proper id:
public ActionResult GetBook(int id) // id = 123456789
{
var book = dataManager.Books.GetBookById(id); // == null
logger.Info("Getting book with id " + book.Id);
return View(book);
}
如果 id
参数无效,则会出现500错误,因为没有书籍带有该ID.
If id
parameter is not valid we get 500 error because there is no book with that id.
如果我们需要抛出404错误,我们必须手动处理这种情况,如下所示:
We have to handle this situation manually if we need to throw 404 error, like this:
if (book == null)
{
return HttpNotFound();
}
是否有可能将Web应用程序中某处的所有操作方法(自定义过滤器,请求管道)的500错误切换为404错误?
Is it possible to switch 500-error to 404-error for all action methods somewhere in web-application (custom filter, request pipeline)?
推荐答案
从技术上讲,您可以通过安装错误处理程序,将500个内部服务器错误重写为在 Application_Error()
中找不到的404,如下所示: ASP.NET MVC 5错误处理中进行了解释.
Technically you could, by installing an error handler, rewrite any 500 Internal Server Error to a 404 Not Found in Application_Error()
as explained in ASP.NET MVC 5 error handling.
但是,您似乎想让代码在 book.Id
中的空 book
上引发 NullReferenceException
,并转为该异常进入404.
However, you seem to want to let your code throw a NullReferenceException
on a null book
in book.Id
, and turn that exception into a 404.
在这种情况下,您真的不应该这样做,因为这会隐藏编程错误,因为您会错过无意间发生的异常.
You really shouldn't be doing that in this case, because this will hide programming errors, because you will miss the exceptions where this happened unintentionally.
所以:只需在您期望 null
的地方明确执行此操作即可.您显示的代码正是您所需要的:
So: just do this explicitly where you do expect a null
. The code you showed is exactly what you need:
if (book == null)
{
return HttpNotFound();
}
这篇关于如果实体对象为null,则自动从操作方法中抛出404异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!