Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - HttpException or return view?

Tags:

asp.net-mvc

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();
}
like image 778
ebb Avatar asked Oct 14 '10 16:10

ebb


2 Answers

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

like image 111
Luke Puplett Avatar answered Oct 15 '22 01:10

Luke Puplett


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.

like image 23
Brian Driscoll Avatar answered Oct 15 '22 03:10

Brian Driscoll