WCF 3.5: UriTemplateMatch

19. August 2007 04:23

Earlier this week, I posted about the new UriTemplate class that will be available in .NET 3.5.  In that post, I mentioned that UriTemplate can be used to to generate a Uri based on a set of parameters.  However, it can also be used to match against an existing Uri and parse the Uri into the parameters defined within the UriTemplate. 

Here is an example:

// Setup a template based on the format of archived posts on my blog.
UriTemplate template = new UriTemplate("portal/blogs/jeff_barnes/archive/{year}/{month}/{day}/*");

// Setup the base address for my blog.
Uri baseAddress = new Uri("http://jeffbarnes.net");

// Create a candidate uri and match against it using the template. 
Uri candidateUri = new Uri("http://jeffbarnes.net/portal/blogs/jeff_barnes/archive/2007/08/14/wcf-3-5-uri-templates.aspx");
UriTemplateMatch match = template.Match(baseAddress, candidateUri);

// Check whether the match was successful.
// Match will be null is the operation failed.
if (match != null)
    // Values within the matched uri can be extracted as the
    // named parameters in the template via the BoundVariables property.
    DateTime postDate = new DateTime(

In this example, a UriTemplate is setup based on the format of the uri for archived posts on my blog.  In the template, the year, month, and day values of the uri have been defined as parameters.  A uri from one of my previous posts is then matched against the template.  This makes it possible to easily extract the named parameters in the template from the actual uri, which is much cleaner than trying to write code that counts the number of slashes, or something similar, in order to manually parse the values. 

To get any real usefulness from UriTemplate, you will quickly come to appreciate UriTemplateMatch.

Comments are closed

About Me

I'm a passionate software developer and advocate of the Microsoft .NET platform.  In my opinion, software development is a craft that necessitates a conscious effort to continually improve your skills rather than falling into the trap of complacency.  I was also awarded as a Microsoft MVP in Connected Systems in 2008, 2009, and 2010.

Can’t code withoutThe best C# & VB.NET refactoring plugin for Visual Studio
Follow jeff_barnes on Twitter

View Jeff Barnes's profile on LinkedIn


Shared Items


Anything you read or see on this site is solely based on my own thoughts.  The material on this site does not necessarily reflect the views of my employer or anyone else.  In other words, I don't speak for anyone other than myself.  So, don't assume I am the official spokesperson for anyone.