Permanently Redirect ActionResults Tutorial

This tutorial illustrates the use of the Permanently Redirect ActionResults that can be found in the DigitallyCreated.Utilities.Mvc assembly. This tutorial assumes you know C# and ASP.NET MVC.

ASP.NET MVC ships with the RedirectResult and the RedirectToRouteResult, which uses an HTTP status code of 302 (Found) to redirect user to another page. DigitallyCreated.Utilities.Mvc provides two new ActionResults, the PermanentRedirectResult and the PermanentRedirectToRouteResult, which perform the same functionality as the ASP.NET MVC ActionResults, except instead of using the status code of 302, they use the status code of 301 (Moved Permanently).

Extension methods to Controller (found in the PermanentRedirectResultExtensions class) have been provided that mimic the usage of the normal Redirect, RedirectToAction and RedirectToRoute. These methods are PermanentlyRedirect, PermanentlyRedirectToAction, and PermanentlyRedirectToRoute. Here is a usage example:

/// <summary>
/// Action method that returns a <see cref="PermanentRedirectResult"/> that redirects to
/// the actual blog post (used to support old permalinks to blogs)
/// </summary>
/// <param name="id">The ID of the blog post</param>
/// <returns>The redirect result</returns>
public ActionResult PermanentlyRedirectToBlog(string id)
    int intId;
    if (Int32.TryParse(id, out intId) == false)
        throw new HttpException(404, "Page not found");

    BlogPost post;
        post = _BlogManager.GetPost(intId, false);
    catch (NotFoundException)
        throw new HttpException(404, "Page not found");

    return this.PermanentlyRedirectToAction("View", new {id, slug = post.Slug});

Note the use of this. when calling PermanentlyRedirectToAction. This is to get access to the extension method, something that is not necessary when using the normal RedirectToAction method, since it is declared as a method on Controller and is not an extension method.

Last edited Mar 23, 2010 at 8:34 AM by dchambers, version 1


No comments yet.