ASP.NET MVC 3: HttpNotFoundResult, RedirectResult, HttpStatusCodeResult

Next to the plain old ActionResult we know from the previous versions, we can now make use of some extra helper classes:

  • HttpNotFoundResult
  • RedirectResult
  • HttpStatusCodeResult

You don’t need to be a rocket scientist to figure out what they will do, but I will add a few examples anyway:

HttpNotFoundResult

Where in the past, you had to create a specific view when an item doesn’t exist, you can now make use of the HttpNotFoundResult action:

public ActionResult Details(int id)
{
    Dinner dinner = dinnerRepository.GetDinner(id);
    if (dinner == null)
    {
        //return View(“NotFound”);
        return new HttpNotFoundResult(“Dinner has been deleted or does not exist”);
    }
    else
    {
        return View(dinner);
    }
}

RedirectResult

Logically redirects you to a given url:

public ActionResult Index()
{
    return new RedirectResult(“https://kevinderudder.wordpress.com”);
}

HttpStatusCodeResult

Give a respond with a specific code and description:

Dinner dinner = dinnerRepository.GetDinner(id);
if (dinner == null)
{
    //return View(“NotFound”);
     return new HttpNotFoundResult(“Dinner has been deleted or does not exist”);
}
else if (dinner.Expired)
{
    return new HttpStatusCodeResult(410);
}

Advertisements