【问题标题】:C# web api parse URL to only get the method method name up till the /C# web api 解析 URL 以仅获取方法方法名称,直到 /
【发布时间】:2017-03-08 22:48:38
【问题描述】:

我有一些 web api url,我用令牌和 api 地址列表限制人们使用它们

之前我一直在寻找他们的令牌,并且它与一个有效的 api 地址相匹配,例如

api/request

我为此编写的代码是

string prefixSearched = "api";
string parsedUrl =  consumer.ApiAddressRequested.Substring(
                        consumer.ApiAddressRequested.IndexOf(prefixSearched, StringComparison.Ordinal) +
                        prefixSearched.Length);
string finalSearch = prefixSearched + parsedUrl;

所以当 URL 是 http://localhost:29001/api/request 时,上面对我有用

但是我意识到我自己和其他人的 api 服务最终看起来像这样

`http://localhost:29001/GetQAByDateTime/date/2-15-2017/time/11`

所以除了锁定主 FQDM 之外,我想我真的只想将 GetQAByDateTime 输入数据库,那么我怎样才能从 url 字符串中解析出来呢?

似乎我需要能够解析出 api/request 之类的东西,然后还有这些没有 api/ 的东西

我认为大多数是api/something 但随后是GetSomething 的异常

【问题讨论】:

    标签: c# api asp.net-web-api


    【解决方案1】:

    可以使用UriTemplate解析url:

    var host = new Uri("http://localhost:29001");
    var apiTemplate = new UriTemplate("{api}/{*params}", true);
    
    var match = apiTemplate.Match(host, new Uri("http://localhost:29001/GetQAByDateTime/date/2-15-2017/time/11"));
    if (match == null)
        throw new ArgumentException();
    
    Console.WriteLine(match.BoundVariables["api"]);     // GetQAByDateTime
    Console.WriteLine(match.BoundVariables["params"]);  // date/2-15-2017/time/11
    

    你可以期待什么:

    +---------------------------------------------------------------+------------------+-------------------------+
    |                              Url                              |       API        |         Params          |
    +---------------------------------------------------------------+------------------+-------------------------+
    | http://localhost:29001/GetSomething                           | GetSomething     |                         |
    | http://localhost:29001/GetSomething2/                         | GetSomething2    |                         |
    | http://localhost:29001/GetQAByDateTime/date/2-15-2017/time/11 | GetQAByDateTime  | date/2-15-2017/time/11  |
    | http://localhost:29001/GetQAByDateTime/dat11                  | GetQAByDateTime  | dat11                   |
    +---------------------------------------------------------------+------------------+-------------------------+
    

    【讨论】:

    • 嘿,所以如果我发布到服务器然后说我把顶行留在那里,但是然后在 new Uri(" 我使用 httpcontext....等...) 那么基本上这不会是一场比赛,它会打破,对吧?var match = apiTemplate.Match(host,etc
    • 我创建一个新问题顺便说一句谢谢stackoverflow.com/questions/42689379/…
    猜你喜欢
    • 2018-12-29
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2012-03-27
    相关资源
    最近更新 更多