MVC 3 XML Sitemap
Ok, so you’ve got your shiny new mvc3 app up and running. Now, it’s time to bake in some of that SEO goodness. Here’s how you can easily add a sitemap.xml to your new mvc application. The solution specified below not only pumps out the xml file to submit to the search engines, but it is also a System.Web.SiteMapProvider, so you can use it for menus and wherever else you want to use your sitemap.
I’m a big fan of NuGet, so bring up the Package Manager Console and grab MvcSiteMapProvider (or download it from github).
Install-Package MvcSiteMapProvider
Once it is installed there will be a new Mvc.sitemap file added with the following to your solution:
<mvcSiteMapNode title="Home" controller="Home" action="Index">
<mvcSiteMapNode title="About" controller="Home" action="About"/>
</mvcSiteMapNode>
Now for the easy bit: to get a ~/sitemap.xml to auto-generate for us based on our controller actions we specified in the sitemap file above. All you need to do is simply add the following to your route registration (generally Global.Application_Start()):
XmlSiteMapController.RegisterRoutes(RouteTable.Routes);
Now, like a lot of other people out there my next question was, what about my dynamically generated content from the database (such as Product/Details/1)? Easy – MvcSiteMapProvider comes with dynamic node support. Just create a class like the following:
public class ProductDetailsDynamicNodeProvider : DynamicNodeProviderBase
{
public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
{
// Create a node for each product
foreach (Product product in productService.GetAllProducts())
{
var node = new DynamicNode();
node.Title = product.Name;
node.RouteValues.Add("id", product.Id);
yield return node;
}
}
public override CacheDescription GetCacheDescription()
{
return new CacheDescription("ProductDetailsDynamicNodeProvider")
{
SlidingExpiration = TimeSpan.FromMinutes(60);
};
}
}
Things to note with the above code: you don’t have to override the cachedescription method, but this does allow us to specify how long all our products will be cached for in the sitemap. Then, you can add your dynamic node to the mvc.sitemap files as follows:
<mvcSiteMapNode title="Details" action="Details" dynamicNodeProvider="Website.ProductDetailsDynamicNodeProvider, Website"/>
Now you are done and have a working auto-generated mvc sitemap. For those of us who are using it to generate breadcrumbs, check out the awesome example of html helpers in the documentation.
Next time, I’ll be looking at creating SEO friendly URLs in MVC.