Adding a Sitemap in ASP.NET MVC3

Anyone who is trying to get their website indexed by search engines should be familiar with sitemaps and what they are used for, but not everyone knows how to go about generating a sitemap. 

Wait, What is a Sitemap Again?

A sitemap is simply an XML file that a website uses to tell search engines about all the different pages on the site.  Search engines can use them to easily discover and index your content, often much quicker than the usual method of crawling your site looking for new links.

There are actually 2 types of sitemaps.  The traditional sitemap lists actual pages in a website.  A sitemap index file points to different sitemaps containing the actual pages.  Since a sitemap file is limited to 50,000 links, a sitemap index allows you to link to multiple sitemaps and avoid the 50,000 link limit.

Who Cares?

I know you are busy building lots of great content and quality links to help build traffic, but you still need to ensure that your site is indexed by the major search engines.  Evidence suggests that a quality sitemap can help increase traffic without any other major changes!

Let’s Do It!

The easiest way to generate a sitemap is to simply generate a static XML file with all your links.  This is simple and there are a variety of tools out there that will do just that.  For example, I might create the following sitemap for http://example.com:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>http://example.com/</loc>
  </url>
  <url>
    <loc>http://example.com/home/Contact</loc>
  </url>
  <url>
    <loc>http://example.com/home/About</loc>
  </url>
  <url>
    <loc>http://example.com/TermsOfService</loc>
  </url>
  <url>
    <loc>http://example.com/Privacy</loc>
  </url>
</urlset>

Once I have a valid sitemap file, I can add it to the root directory of my website (I am assuming it is called “sitemap.xml”) and tell MVC to ignore routing requests for that file:

routes.IgnoreRoute("sitemap.xml");

This makes it so MVC will simply return the sitemap.xml file when you navigate to “yoursite.com/sitemap.xml”.  That is all it takes to add a static sitemap to your website.

Of course, if you have a large number of pages or new pages get added, generating this by hand can become quite cumbersome.  That is when it becomes useful to generate the sitemap dynamically.