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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: