给定一个 Uri 和一个 UriTemplate,如何获取模板参数值? [英] Given a Uri and a UriTemplate, how to get template parameter values?

查看:31
本文介绍了给定一个 Uri 和一个 UriTemplate,如何获取模板参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我可以访问 Uri 和所基于的 UriTemplate,发现替换模板中参数的值的最简洁方法是什么?

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?

例如,如果我知道:

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

是否有一种内置方法可以让我发现 categoryName = "foo" 和 productName = "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);

parameterValues 的位置:

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.

谢谢

桑迪

推荐答案

您可以致电Match 方法在 uriTemplate 实例上并使用返回的 UriTemplateMatch 实例来访问参数值:

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]);
}

输出

CATEGORYNAME: foo
PRODUCT-NAME: bar

这篇关于给定一个 Uri 和一个 UriTemplate,如何获取模板参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆