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. It's not about being a REST disciple, it's just how the web works.
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. No question about that.
Edit: This is good guidance: 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.
REST disciples will likely tell you to go the HTTP Exception route because they believe that a URI identifies a conceptual resource (i.e.: 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.
However, some will disagree and say that you should only pass back a 404 error if the physical resource, e.g. a file, doesn't exist.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With