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

柔情痞子 提交于 2019-12-11 02:46:03

问题


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


回答1:


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



回答2:


Note the key used in this fix is incorrect, "currently" in .net 4.5 the key is MS_DirectRouteMatches.

routeData.Values["MS_SubRoutes"] should be routeData.Values["MS_DirectRouteMatches"]).



来源:https://stackoverflow.com/questions/24665016/is-it-possible-to-get-route-data-on-runtime-outside-of-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!