Skip to main content
 首页 » 编程设计

c#之如何在给定 HttpRequestMessage 的情况下检索路由模板变量

2024年02月13日12lonelyxmas

我有两个 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 中可用。