Didsbury Design Blog

Canonical URLs in your ASP.NET MVC2 / MVC3 Application

November 15th, 2010

What are canonical links used for
The Canonical link element was introduced in 2009 to help cleanup duplicate pages on search engines.
The html code is shown below and it basically informs search engines of the primary URL for that page. This means any alternative entry points to that page will not be picked up as duplicate content. This HTML must be specified in the HEAD section of the document.

<link rel="canonical" href="http://example.com/page.html"/>

The search engines have also posted about this on a Google blog post or help center documentation from Google, Yahoo’s blog post, or Microsoft’s blog post.

How to easily use canonical links in MVC2 using Action Filters and Master Pages

Add this to the master page in the head section as follows:

    <%=ViewData["CanonicalURL"] %>
    <!--Your other head info here-->

Create a Filter Attribute (CanonicalURL.cs):

public class CanonicalURL : ActionFilterAttribute
{
    public string Url { get; private set; }
 
    public CanonicalURL(string url)
    {
       Url = url;
    }
 
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        string fullyQualifiedUrl = "http://www.example.com" + this.Url;
        filterContext.Controller.ViewData["CanonicalUrl"] = @"<link rel='canonical' href='" + fullyQualifiedUrl + "' />";
        base.OnResultExecuting(filterContext);
    }
}

Call this from your actions:

[CanonicalURL("Contact-Us")]
public ActionResult Index()
 {
      ContactFormViewModel contact = new ContactFormViewModel(); 
      return View(contact);
}

For some other interesting articles on Search Engine Related posts check out Matt Cutts blog

ASP.NET MVC 3 Release Candidate is now available

November 10th, 2010

ASP.NET MVC 3 Release Candidate is now available for download. Phil Haack has written an article about it and also mentions the intentions for MVC 4.

Phil Haack’s blog post: ASP.NET MVC 3 Release Candidate

Direct download: MVC 3 RC Download

How to: Create and Delete a cookie in ASP.NET C#

April 29th, 2010

I thought I would do a quick post about Creating and more importantly Deleting cookies in ASP.NET as it’s not quite as obvious as it may seem with the misleading .Remove() method which doesnt do as you would expect.

I hope this helps someone get started with cookies if your just getting started with the .NET framework.

Creating a cookie

This is a basic example of how to create a cookie in ASP.NET C#

//Create a new cookie, passing the name into the constructor
HttpCookie cookie = new HttpCookie("MyCookie");

//Set the cookies value
cookie.Value = "CookieValue";

//Set the cookie to expire in 1 day
cookie.Expires = DateTime.Now.AddDays(1);

//Add the cookie
Response.Cookies.Add(cookie);

Deleting a cookie

When deleting a cookie all you need to do is amend the HttpCookie object so it has an expiry date in the past, then re-save the cookie to push the new value to the client.

// Clear cookie Info
            if(Request.Cookies["MyCookie"]!=null){

                HttpCookie cookie = Request.Cookies["MyCookie"];
                cookie.Expires = DateTime.Now.AddDays(-1);

                Response.Cookies.Add(cookie);
            }

How to: Allow hyphens in URL’s using ASP.NET MVC 2

February 6th, 2010

If you wan’t to allow hyphens in your URL’s you will need to change the way the routing works in your Global.asax file.

First create a new class which extends the MvcRouteHandler and place this in the Global.asax file after the main MvcApplication class.

C#:

public class HyphenatedRouteHandler : MvcRouteHandler{
	protected override IHttpHandler  GetHttpHandler(RequestContext requestContext)
	{
		requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
		requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
		return base.GetHttpHandler(requestContext);
	}
}

VB:

Public Class HyphenatedRouteHandler
    Inherits MvcRouteHandler
 
    Protected Overrides Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler
        requestContext.RouteData.Values("controller") = requestContext.RouteData.Values("controller").ToString.Replace("-", "_")
        requestContext.RouteData.Values("action") = requestContext.RouteData.Values("action").ToString.Replace("-", "_")
        Return MyBase.GetHttpHandler(requestContext)
    End Function
 
End Class

Then you need to replace the routes.MapRoute with an equivalent routes.Add specifying the new handler as the MapRoute does not allow you to specify a custom route handler.

C#:

routes.Add(
	new Route("{controller}/{action}/{id}", 
		new RouteValueDictionary(
			new { controller = "Default", action = "Index", id = "" }),
			new HyphenatedRouteHandler())
);

VB:

routes.Add(New Route("{controller}/{action}/{id}", 
	New RouteValueDictionary(New With {.controller = "Home", .action = "Index", .id = ""}), 
		New HyphenatedRouteHandler()))

I hope this is useful, any questions feel free to get in touch.

Would like to say thanks to John from here for answering the original question on Stackoverflow