使用 UriTemplate 检查部分 URL 的 Web api 调用无法正常工作

web api call with checking part of the URL using UriTemplate not working correctly

可能是我不明白如何正确使用UriTemplate

我一直想在传入的 url 中搜索

api/whatever      // that is it 

如果 URL 如下所示,我只想得到 api/CheckMainVerified 所以我想如果不使用 UriTemplate,我想子字符串检查或正则表达式会起作用吗?

http://localhost:29001/api/CheckMainVerified/223128

这就是我在做的事情

var url = "http://localhost:29001/api/CheckMainVerified/223128";


//var host = new Uri(serverHost.AbsoluteUri);
var host = new Uri("http://localhost:29001");

var apiTemplate = new UriTemplate("{api}/{*params}", true);

var match = apiTemplate.Match(host, new Uri(url));

var finalSearch = match.BoundVariables["api"];
string parameters = match.BoundVariables["params"];

finalSearch.Dump();
parameters.Dump();
match.Dump();

我认为您只是缺少模板中的第二个选项(参见下面的示例)。

var template = new UriTemplate("{api}/{controller}/{*params}", true);
var fullUri = new Uri("http://localhost:29001/api/CheckMainVerified/223128");
var prefix = new Uri("http://localhost:29001");
var results = template.Match(prefix, fullUri);

if (results != null)
{
    foreach (string item in results.BoundVariables.Keys)
    {
        Console.WriteLine($"Key: {item}, Value: {results.BoundVariables[item]}");
        // PRODUCES:
        // Key: API, Value: api
        // Key: CONTROLLER, Value: CheckMainVerified
        // Key: PARAMS, Value: 223128
    }

    Console.WriteLine($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}");
    // PRODUCES:
    // api/CheckMainVerified
}

因此,将“{controller}”添加到模板应该可以解决您的问题。 从那里,您可以进行简单的字符串比较。 即

if ($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}" == "api/CheckMainVerified") { ... }

或者,按照您的建议;您可以使用子字符串或正则表达式解决方案。