The Blog of Ian Mercer.

Building sitemap.xml for SEO ASP.NET MVC

Creating a sitemap.xml file for Google and other search engines can be accomplished in MVC using a simple ActionResult that returns the appropriate XML blog. The problem however is in generating the list of URLs to go into that sitemap.xml file.

In ASP.NET MVC there is no distinction between an action method that is a page and one that is a service call. To remedy that let's create an ActionFilterAttribute that can be applied to any method to mark it as a page and to record the URL that we want that page to show up as in our sitemap:

/// \<summary\>
/// This attribute indicates that a method is an actual page and gives the data for it
/// \</summary\>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MVCUrlAttribute : ActionFilterAttribute
{
	public string Url { get; private set; }
	
	public MVCUrlAttribute(string url)
	{
	this.Url = url;
	}
	
	public override void OnResultExecuting(ResultExecutingContext filterContext)
	{
	string fullyQualifiedUrl = filterContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + this.Url;
	// We build HTML here because we want the View to be easily able to include it without any conditionals
	// and because the ASP.NET WebForms view engine sometimes doesn't subsitute \<% in certain head items
	filterContext.Controller.ViewData["CanonicalUrl"] = @"\<link rel=""canonical"" href=""" + fullyQualifiedUrl + " /\>";
	base.OnResultExecuting(filterContext);
	}
}

You may wonder at this point why we can't just use the Routing table to figure this out. The issue is that multiple routes may map onto one page but we still want it to show up just once in the sitemap otherwise we will get slammed for duplicate content. We also want to be able to mark each page with its canonical URL.

Now we can use reflection to find all of the 'pages' in our ASP.NET MVC Application and then build a sitemap.xml file from them.

	List<string> allPageUrls = new List\<string\>();
	// Find all the MVC Routes
	Log.Debug("*** FINDING ALL MVC ROUTES MARKED FOR INCLUSION IN SITEMAP");
	var allControllers = Assembly.GetExecutingAssembly().GetTypes().Where(t =\> t.IsSubclassOf(typeof(Controller)));
	Log.DebugFormat("Found {0} controllers", allControllers.Count());
	foreach (var controllerType in allControllers)
	{
	  var allPublicMethodsOnController = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
	  Log.DebugFormat("Found {0} public methods on {1}", allPublicMethodsOnController.Count(), controllerType.Name);
	  foreach (var publicMethod in allPublicMethodsOnController)
	  {
	    var mvcurlattr = publicMethod.GetCustomAttributes(true).OfType\<MVCUrlAttribute\>().FirstOrDefault();
	    if (mvcurlattr != null)
	    {
	      string url = mvcurlattr.Url;
	      Log.Debug("Found " + controllerType.Name + "." + publicMethod.Name + " \<-- " + url);
	      allPageUrls.Add(url);
	    }
	  }
	}

Related Stories

Xamarin Forms Application For Home Automation

Building a Xamarin Forms application to control my home automation system

Ian Mercer
Ian Mercer

JSON Patch - a C# implementation

Ian Mercer
Ian Mercer

Dynamically building 'Or' Expressions in LINQ

How to create a LINQ expression that logically ORs together a set of predicates

Ian Mercer
Ian Mercer

VariableWithHistory - making persistence invisible, making history visible

A novel approach to adding history to variables in a programming language

Ian Mercer
Ian Mercer

Updated Release of the Abodit State Machine

A hierarchical state machine for .NET

Ian Mercer
Ian Mercer

Building a better .NET State Machine

A state machine for .NET that I've released on Nuget

Ian Mercer
Ian Mercer

The Internet of Dogs

Connecting our dog into the home automation

Ian Mercer
Ian Mercer

A simple state machine in C#

State machines are useful in many contexts but especially for home automation

Ian Mercer
Ian Mercer

Closing down seokeywordsearch.com

Ian Mercer
Ian Mercer

Convert a property getter to a setter

Ian Mercer
Ian Mercer

Web site crawler and link checker (free)

Ian Mercer
Ian Mercer

MongoDB Map-Reduce - Hints and Tips

Ian Mercer
Ian Mercer

Weather Forecasting for Home Automation

Ian Mercer
Ian Mercer

Lengthening short Urls in C#

Ian Mercer
Ian Mercer

SEO Myths

Ian Mercer
Ian Mercer

ASP.NET MVC SEO - Solution Part 1

Ian Mercer
Ian Mercer

Seo for beginners

Ian Mercer
Ian Mercer

SEO Keyword Tool in Action

Ian Mercer
Ian Mercer

Tip: getting the index in a foreeach statement

A tip on using LINQ's Select expression with an index

Ian Mercer
Ian Mercer

WCF and the SYSTEM account

Namespace reservations and http.sys, my, oh my!

Ian Mercer
Ian Mercer

404 errors on IIS6 with ASP.NET 4 Beta 2

Ian Mercer
Ian Mercer

Mixed mode assembly errors after upgrade to .NET 4 Beta 2

Fixing this error was fairly simple

Ian Mercer
Ian Mercer

The EntityContainer name could not be determined

How to fix the exception "the entitycontainer" name could not be determined

Ian Mercer
Ian Mercer

Shortened URLs should be treated like a Codec ...

Expanding URLs would help users decide whether or not to click a link

Ian Mercer
Ian Mercer

A great site for developing and testing regular expressions

Just a link to a site I found useful

Ian Mercer
Ian Mercer

Entity Framework in .NET 4

Ian Mercer
Ian Mercer

System.Data.EntitySqlException

Hints for dealing with this exception

Ian Mercer
Ian Mercer

Exception Handling using Exception.Data

My latest article on CodeProject covers the lesser known Exception.Data property

Ian Mercer
Ian Mercer

ASP.NET Custom Validation

How to solve a problem encountered with custom validation in ASP.NET

Ian Mercer
Ian Mercer

Optimization Advice

Some advice on software optimization

Ian Mercer
Ian Mercer

Linq's missing link

LinqKit came in handy back in 2009

Ian Mercer
Ian Mercer

Cache optimized scanning of pairwise combinations of values

Using space-filling curves to optimize caching

Ian Mercer
Ian Mercer

Threading and User Interfaces

A rant about how few software programs get threading right

Ian Mercer
Ian Mercer