开发者

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

开发者 https://www.devze.com 2023-04-08 01:43 出处:网络
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?

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号