c# - 给定一个 Uri 和一个 UriTemplate,如何获取模板参数值?

标签 c# uri

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

例如,如果我知道:

        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"?

我希望找到这样的方法:

        var parameterValues = uriTemplate.GetParameterValues(uri);

parameterValues 在哪里:

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

显然,我可以自己编写,但我想知道框架中是否有我可以使用的东西。

谢谢

桑迪

最佳答案

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

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

关于c# - 给定一个 Uri 和一个 UriTemplate,如何获取模板参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7546043/

相关文章:

C# Httpclient FormUrlEncodedContent 编码

c# - 如果登录不正确,如何使 C# WCF session 无效

ruby - URI.escape 的简单替代方案

xml - 创建没有域的 XML 命名空间

java - 在java中获取AppData路径时URI语法错误

c# - Outlook 插件 - 获取当前选定的日历日期

c# - SQL Server CE 回滚不会撤消删除

c# - .Net 为什么GC不从堆中删除对象?

ruby-on-rails - 在 RSpec 测试中模拟子 uri

java - 带有特殊字符的 URI.getHost()