c# - 如何检索给定 HttpRequestMessage 的路由模板变量?

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

我有两个 API Controller ,位于两个不同的文件夹中,其中有 GetEvents() 操作:

V1
  EventsController

V2
  EventsController

我希望能够使用以下方式访问 Controller :

 api/v1/events and api/v2/events

我的路线模板如下所示

api/v{version}/{controller}

私有(private)静态字符串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 检索此类数据的标准方法是什么?

最佳答案

尝试,

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

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

关于c# - 如何检索给定 HttpRequestMessage 的路由模板变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16420155/

相关文章:

javascript - AngularJS:如何在服务中模型更改时更改 ng-repeat 中的数据

c# - WPF 命令不适用于 MVVM 应用程序中的子菜单项

c# - 委托(delegate)大会的主要流程是什么?

c# - 在 C# 中使用图像路径从 Oracle 数据库中检索图像

c# - 使用 DataSource 在 Dropdownlist 中进行数据操作

spring - 如何从 <form :select> Spring MVC 传递数据

cakephp - 在app_controller中设置一个变量,并在CakePHP布局中使用它

c# - 从 Web API 返回时 Zip 损坏?

c# - 如何将按钮添加到 TabPage 的页眉?

c# - DropDownlistFor MVC 4 中的 Optgroup?