sandy
sandy

Reputation: 913

Given a Uri and a UriTemplate, how to get template parameter values?

If I have access to both a Uri and the UriTemplate on which is is based, what is the neatest way to discover the values that have replaced the parameters in the template?

For example, if I know:

        var uriTemplate = new UriTemplate("/product-catalogue/categories/{categoryName}/products/{product-name}");
        var uri = new Uri("/product-catalogue/categories/foo/products/bar");

is there a built-in way for me to discover that categoryName = "foo" and productName = "bar"?

I was hoping to find a method like:

        var parameterValues = uriTemplate.GetParameterValues(uri);

where parameterValues would be:

         { { "categoryName", "foo" }, { "productName", "bar" }}

Clearly, I could write my own, but I was wondering if there was something in framework I could use.

Thanks

Sandy

Upvotes: 4

Views: 2715

Answers (1)

Jeff Ogata
Jeff Ogata

Reputation: 57793

You can call the Match method on the uriTemplate instance and use the returned UriTemplateMatch instance to access the parameter values:

var uriTemplate = new UriTemplate("/product-catalogue/categories/{categoryName}/products/{product-name}"); 
var uri = new Uri("http://www.localhost/product-catalogue/categories/foo/products/bar"); 
var baseUri = new Uri("http://www.localhost");

var match = uriTemplate.Match(baseUri, uri);

foreach (string variableName in match.BoundVariables.Keys)
{
    Console.WriteLine("{0}: {1}", variableName, match.BoundVariables[variableName]);
}

outputs

CATEGORYNAME: foo
PRODUCT-NAME: bar

Upvotes: 3

Related Questions