A slight Nitpick/Improvement for Tekpubs Video about ASP.net MVC Routing

Tekpubs series about ASP.net MVC 2 is really useful and has tons and tons of great tips and code samples, and the episode about Routing (#12) is no exception. However, there is one thing I really didn't like about it.

Around 30 Minutes in when discussing SEO Optimizations, they show a great tip how to enforce canonical URLs. Unfortunately, they do it by modifying the Response object directly. Basically the code looks like

// This snippet doesn't make much sense if you haven't
// watched the Episode, sorry.
public ViewResult Details(int id)
{
    //snipped some parts
    EnforceCanonicalUrl(jobAd.DetailsRouteValues());
    return View(jobAd);
}

private void EnforceCanonicalUrl(RouteValueDictionary routeValues)
{
    if(someCheckFails){
        Response.RedirectLocation = someLocation;
        Response.StatusCode = (int)HttpStatusCode.MovedPermanently;
        Response.End();
    } 
}

This doesn't follow the MVC pattern, and the speaker even acknowledges it in the video as it makes unit testing hard. The proper way is to return an ActionResult from the ControllerAction instead. As I happen to have already written a PermanentRedirectResult, my suggestion to improve this code is this:

public ActionResult Details(int id)
{
    //snipped some parts
    var enforcedResult = EnforceCanonicalUrl(jobAd.DetailsRouteValues());
    // As View and enforcedResult have different types, I cannot use the ?? operator
    if(enforcedResult != null) return enforcedResult;
    return View(jobAd);
}

private PermanentRedirectResult EnforceCanonicalUrl(RouteValueDictionary routeValues)
{
    if(someCheckFails){
        return new PermanentRedirectResult(canonicalPathAndQuery);
    } else {
       return null;
    }
}

So I changed the return type of the controller action to ActionResult instead of ViewResult, and I gave EnforceCanonicalUrl a return type. This function now either returns null or a PermanentRedirectResult, and the controller action now checks for it. There are of course more ways to refine it, but it is in line with the ASP.net MVC pattern of having Controller Actions return ActionResults instead of modifying the Response directly.

Comments (1)

ASP.NET MVC Archived Blog Posts, Page 1March 30th, 2010 at 05:07

[...] to VoteA slight Nitpick/Improvement for Tekpubs Video about ASP.net MVC Routing (3/27/2010)Saturday, March 27, 2010 from mstumTekpub's series about ASP.net MVC 2 is really useful and has tons [...]