Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用UriTemplate检查部分URL的web api调用无法正常工作_C#_Regex_Asp.net Web Api_Substring_Uritemplate - Fatal编程技术网

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

C# 使用UriTemplate检查部分URL的web api调用无法正常工作,c#,regex,asp.net-web-api,substring,uritemplate,C#,Regex,Asp.net Web Api,Substring,Uritemplate,也许我不明白如何正确使用UriTemplate 我总是想在传入的url中搜索 api/whatever // that is it 如果URL如下所示,我只想得到api/checkmain验证 所以我想如果不使用UriTemplate,我想子字符串检查或正则表达式可以工作吗 http://localhost:29001/api/CheckMainVerified/223128 这就是我在做的 var url = "http://localhost:29001/api/CheckM

也许我不明白如何正确使用
UriTemplate

我总是想在传入的url中搜索

api/whatever      // that is it 
如果URL如下所示,我只想得到
api/checkmain验证
所以我想如果不使用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();

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

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

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

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
}
if ($"{results.BoundVariables["api"]}/{results.BoundVariables["controller"]}" == "api/CheckMainVerified") { ... }