15

Is there any way to statically get route values from a service method (outside of a controller) that is running in a Web API context? For example, I can do the following in ASP.NET MVC:

var mvcHandler = HttpContext.Current.Handler as MvcHandler;
var routeValues = mvcHandler.RequestContext.RouteData.Values;

I'd like to find the equivalent version of this code for Web API.

When I try to debug a sample Web API request and look at HttpContext.Current.Handler it is of type HttpControllerHandler, but this type doesn't have any properties to access route data.

EDIT

To try to help provide some more information. The code I am trying to read the value from is inside of a factory class I have that builds a custom object for my application.

4

2 回答 2

20

您可以在 HttpRequestMessage 上使用 GetRouteData() 扩展。您需要包含 System.Net.Http 命名空间才能获得此信息。

System.Web.Http.Routing.IHttpRouteData routeData = Request.GetRouteData();
于 2013-05-13T17:55:09.327 回答
13

我能够找到一个解决方案,可以获取 MVC 请求或 Web API 请求的路由值。

HttpContext.Current.Request.RequestContext.RouteData
于 2013-05-13T18:02:56.900 回答