【问题标题】:How to retrieve a route template variable given the HttpRequestMessage?如何在给定 HttpRequestMessage 的情况下检索路由模板变量?
【发布时间】:2013-05-07 13:20:06
【问题描述】:

我有两个 API 控制器位于两个具有 GetEvents() 操作的不同文件夹中:

V1
  EventsController

V2
  EventsController

我希望能够使用以下方式访问控制器:

 api/v1/events and api/v2/events

我的路线模板如下所示

api/v{version}/{controller}

私有静态字符串 GetRequestVersion(HttpRequestMessage 请求) {

// 如何从 url 中找到 {version} 的值?

}

我使用 REGEX 编写了一个运行良好的代码:

 private static string ExtractVersionFromUrl(HttpRequestMessage request)
        {
            Match match = Regex.Match(request.RequestUri.PathAndQuery, @"/v(?<version>\d+)/", RegexOptions.IgnoreCase);

            return match.Success ? match.Groups["version"].Value : null;
        }

从 uri 检索此类数据的标准方法是什么?

【问题讨论】:

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


    【解决方案1】:

    试试,

    Request.GetRouteData().Values["version"];
    

    GetRouteData 是一种扩展方法,在命名空间System.Net.Http 中可用。

    【讨论】:

      【解决方案2】:

      我在冒险猜测返回值。另一种方法是简单地将其定义为控制器中方法中的参数,如下所示:

      public IEnumerable<Event> GetEvents(string version, HttpRequestMessage request) {
      ...
      }
      

      这是我自己想出来的。 Web API 很漂亮!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-24
        • 2019-10-14
        • 1970-01-01
        • 2017-07-25
        • 2021-03-22
        • 1970-01-01
        相关资源
        最近更新 更多