Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 227
Kyle Avatar asked May 13 '13 17:05

Kyle


2 Answers

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();
like image 153
Kiran Avatar answered Nov 07 '22 01:11

Kiran


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
like image 32
Kyle Avatar answered Nov 07 '22 01:11

Kyle