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(
Convert.ToInt32(match.BoundVariables["year"]),
Convert.ToInt32(match.BoundVariables["month"]),
Convert.ToInt32(match.BoundVariables["day"]));
}
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.
f4b0c421-2cb5-4292-a3d6-a8fa5746c4ae|0|.0
By: Jeff Barnes
Category:
Tags: