Kyle
Kyle

Reputation: 4376

Web API get route values

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.

Upvotes: 15

Views: 22404

Answers (2)

Kyle
Kyle

Reputation: 4376

I was able to find a solution that would get the route values for either an MVC request or a Web API request.

HttpContext.Current.Request.RequestContext.RouteData

Upvotes: 13

Kiran
Kiran

Reputation: 57999

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();

Upvotes: 20

Related Questions