[英]ASP.NET MVC - HttpException or return view?
I'm trying to make a request for a customer and if the customer doesn't exist it should return some kind of "Not found" page. 我正在尝试向客户提出请求,如果客户不存在,则应返回某种“未找到”页面。 Which of the below would be the best practice to use for such a task, and why? 以下哪项是用于此类任务的最佳实践,为什么?
public ActionResult Index(int id)
{
if (customerService.GetCustomerById(id) == null)
return View("NotFound");
return View();
}
or 要么
public ActionResult Index(int id)
{
if (customerService.GetCustomerById(id) == null)
throw new HttpException(404, "Customer not found");
return View();
}
Throw a 404. There's really no argument. 扔了404.真的没有争论。 It's not about being a REST disciple, it's just how the web works. 这不是成为一名REST门徒,而是网络的运作方式。
You can return a view and a 404. It's often helpful to help the user or present a search box or point to some top selling items, but make the NotFound clear to the customer and always return a 404 in the HTTP response. 您可以返回视图和 404.帮助用户或提供搜索框或指向某些畅销商品通常很有帮助,但是对客户明确NotFound并始终在HTTP响应中返回404。 No question about that. 毫无疑问。
Edit: This is good guidance: http://www.codinghorror.com/blog/2007/03/creating-user-friendly-404-pages.html 编辑:这是一个很好的指导: http : //www.codinghorror.com/blog/2007/03/creating-user-friendly-404-pages.html
This is a good question (+1) as there are some differing opinions out there about when to use HTTP exception codes and when not. 这是一个很好的问题(+1),因为对于何时使用HTTP异常代码存在一些不同的意见,何时没有。
REST disciples will likely tell you to go the HTTP Exception route because they believe that a URI identifies a conceptual resource (ie: the actual object/thing to which you are referring - a Customer in this case), and if that resource doesn't exist then you should get a 404 error back. REST门徒可能会告诉您转到HTTP异常路由,因为他们认为URI标识了一个概念资源(即:您所指的实际对象/事物 - 在这种情况下是一个客户),如果该资源没有存在然后你应该得到404错误。
However, some will disagree and say that you should only pass back a 404 error if the physical resource, eg a file, doesn't exist. 但是,有些人会不同意并且说如果物理资源(例如文件)不存在,则应该仅传回404错误。
I tend to fall into the second camp and would recommend that you return 200 OK with a custom view stating that the customer specified by the ID could not be found. 我倾向于进入第二阵营,并建议您返回200 OK并使用自定义视图说明无法找到ID指定的客户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.