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

╄→尐↘猪︶ㄣ 提交于 2019-12-23 12:35:00

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/7546043/given-a-uri-and-a-uritemplate-how-to-get-template-parameter-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!