If I have access to both a Uri and the UriTemplate on which is is based, what is the neatest way to discover the val开发者_StackOverflowues 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
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
精彩评论