Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.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# 如何在给定HttpRequestMessage的情况下检索路由模板变量?_C#_Asp.net_Controller_Versioning_Asp.net Web Api - Fatal编程技术网

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

C# 如何在给定HttpRequestMessage的情况下检索路由模板变量?,c#,asp.net,controller,versioning,asp.net-web-api,C#,Asp.net,Controller,Versioning,Asp.net Web Api,我有两个API控制器,位于两个不同的文件夹中,其中包含GetEvents()操作: 我希望能够使用以下方式访问控制器: api/v1/events and api/v2/events 我的路线模板如下所示 api/v{version}/{controller} 私有静态字符串GetRequestVersion(HttpRequestMessage请求) { //如何从url中找到{version}值 } 我使用正则表达式编写了一段代码,效果很好: private static strin

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

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

 api/v1/events and api/v2/events
我的路线模板如下所示

api/v{version}/{controller}
私有静态字符串GetRequestVersion(HttpRequestMessage请求) {

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

}

我使用正则表达式编写了一段代码,效果很好:

 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;
        }
private static string extractionversionfromURL(HttpRequestMessage请求)
{
Match Match=Regex.Match(request.RequestUri.PathAndQuery,@“/v(?\d+/”,RegexOptions.IgnoreCase);
返回match.Success?match.Groups[“version”]。值:null;
}
从uri检索此类数据的标准方法是什么?

试试

Request.GetRouteData().Values["version"];
GetRouteData
是一种扩展方法,可在命名空间
System.Net.Http
中找到

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

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

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

public IEnumerable<Event> GetEvents(string version, HttpRequestMessage request) {
...
}
public IEnumerable GetEvents(字符串版本,HttpRequestMessage请求){
...
}

这是我自己想出来的。WebAPI真漂亮

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

public IEnumerable<Event> GetEvents(string version, HttpRequestMessage request) {
...
}
public IEnumerable GetEvents(字符串版本,HttpRequestMessage请求){
...
}
这是我自己想出来的。WebAPI真漂亮