Web API get route values

asp.net-web-apiasp.net-web-api-routing

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.

Best Answer

You can use GetRouteData() extension on HttpRequestMessage. You would need to include System.Net.Http namespace to get this.

System.Web.Http.Routing.IHttpRouteData routeData = Request.GetRouteData();