Sitemaps

By
Dave
Project
Published
10 Jul 2010 17:19
Last Modified
13 Jan 2013 18:20

As part of optimising the results from search engines such as Bing and Google, I added a dynamic site map. The structure of this file is defined by sitemaps.org. In order to generate a suitable file, I added a simple action as shown below in Listing 1.

public ContentResult Sitemap()
{
    XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
    XElement root = new XElement(xmlns + "urlset");

    // home
    root.Add(GetUrlElement(xmlns, ""));

    // posts, categories etc
    foreach (...)
    {
        string url = Url.RouteUrl("MyRoute", new { myparam = value });
        root.Add(GetUrlElement(xmlns, url);
    }

    return Content(root.ToString(), "text/xml", Encoding.UTF8);
}

private XElement GetUrlElement(XNamespace xmlns, string relativeUri)
{
    return new XElement(xmlns + "url",
        new XElement(xmlns + "loc", new Uri(Request.Url, relativeUri).AbsoluteUri));
}

Listing 1. Action to generate dynamic sitemap

While not shown above in Listing 1, I also added <lastmod /> elements, e.g. which corresponded to the last-modified date of a post. The final step was to add a suitable route to global.asax, as shown below in Listing 2.

routes.MapRoute(
    "Sitemap",
    "sitemap.xml",
    new { controller = "MyController", action = "Sitemap" }
);

Listing 2. Sitemap route

The sitemap is then available at http://{domain}/sitemap.xml and can be submitted to search engines using their webmaster tools. For Bing, the webmaster pages can be found at http://www.bing.com/webmaster. For Google the link is http://www.google.com/webmasters/tools.

Add Comment

*
*
*
Captcha
*
*Required