August 6, 2012

Generating dynamic XML Sitemaps in ASP.NET MVC

Sitemaps provide a way of informing search engines about pages in your site. For small websites you could probably generate an XML sitemap file manually. For large sites with dynamic content, a programmatic approach is required.

Essentially a XML sitemap is just a list of URLs with optional metadata such as when it was last updated and how important the URL is.

You can view an example sitemap (from my blog) at http://ben.onfabrik.com/sitemap.

Generating the sitemap

Fortunately I’ve done most of the work for you and pushed the code up to Fabrik.Common.

To generate a sitemap your content can either implement the ISitemapItem interface or just create an instance of the Sitemapitem class.

The SitemapItem constructor conforms to the Sitemaps XML format specification so only the URL location is required. You can optionally provide the Last Modified, Change Frequency or Priority parameters.

I’ve also created a dedicated Action Result, SitemapResult, for generating the sitemap. You can optionally provide your own ISitemapGenerator implementation if you require.

The sample below demonstrates how we can generate a sitemap using the above classes:

public class SitemapController : Controller
{
    // GET: /Sitemap/

    public ActionResult Index()
    {
        var sitemapItems = new List<SitemapItem>
        {
            new SitemapItem(Url.QualifiedAction("index", "home"), changeFrequency: SitemapChangeFrequency.Always, priority: 1.0),
            new SitemapItem(Url.QualifiedAction("about", "home"), lastModified: DateTime.Now),
            new SitemapItem(PathUtils.CombinePaths(Request.Url.GetLeftPart(UriPartial.Authority), "/home/list"))
        };

        return new SitemapResult(sitemapItems);
    }
}

Note: You should return fully qualified URLs in your Sitemap. Fabrik.Common includes the QualifiedAction extension method for generating full qualified Action URLs and the PathUtils.CombinePaths utility function for combining paths manually.

Navigating to /sitemap will produce a valid XML sitemap:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
	<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" 
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
			xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
  <url>
    <loc>http://localhost:55975/</loc>
    <changefreq>always</changefreq>
    <priority>1</priority>
  </url>
  <url>
    <loc>http://localhost:55975/home/about</loc>
    <lastmod>2012-08-06</lastmod>
  </url>
  <url>
    <loc>http://localhost:55975/home/list</loc>
  </url>
</urlset>

You are now free to submit your sitemap to Google.

And don’t forget to include the sitemap URL inside robots.txt:

User-agent: *
Disallow:

Sitemap: http://ben.onfabrik.com/sitemap

© 2022 Ben Foster