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 In order to generate a suitable file, I added a simple action as shown below in Listing 1.

public ContentResult Sitemap()
    XNamespace xmlns = "";
    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.

    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 For Google the link is

Add Comment