Is it possible to get route data on runtime outside of controller?

asp.net, asp.net-mvc, asp.net-mvc-routing, c#

Solution

WebApi has it's own nested RouteData, this is because it doesn't use the `RouteData` class in `System.Web` but it's own `HttpRouteData` class.

The WebApi routing adds an entry under the key `MS_SubRoutes`, which WebApi uses for it's internal routes.

I've written an extension method which flattens the WebApi route data into a `string/object` dictionary, which is what you might see in `RouteData.Values`

WebApiExtensions.cs

public static class WebApiExtensions
{
    public static IDictionary<string, object> GetWebApiRouteData(this RouteData routeData)
    {
        if (!routeData.Values.ContainsKey("MS_SubRoutes"))
            return new Dictionary<string,object>();

        return ((IHttpRouteData[])routeData.Values["MS_SubRoutes"]).SelectMany(x => x.Values).ToDictionary(x => x.Key, y => y.Value);
    }
}

Usage:

[RoutePrefix("projects")]
public class UsergroupController : ApiController
{
    [Route("{projectId}/usergroups"), HttpGet]
    public IHttpActionResult Get()
    {
        // Url: /projects/123/usergroups
        // Response: null
        object value = null;

        var webApiRouteData = HttpContext.Current.Request.RequestContext.RouteData.GetWebApiRouteData();
        value = webApiRouteData["projectId"];

        return Ok(value);
    }
}

Problem

I wonder if it's possible to somehow get the route value outside of controller? This is what I've tried. I also tried to do `.Values["{projectId}"];` but I still get `null`. ``` [RoutePrefix("projects")] public class UsergroupController : ApiController { [Route("{projectId}/usergroups"), HttpGet] public IHttpActionResult Get() { // Url: /projects/123/usergroups // Response: null var projectId = HttpContext.Current.Request.RequestContext.RouteData.Values["projectId"]; return Ok(projectId); } } ``` I found that it is located, but in a very strange matter. Maybe there might be some kind of LINQ query to get it? RouteData-Values-Values-0-0-Values-0

Original source