如何在WebApi中获取区域名称?

时间:2016-09-09 14:12:32

标签: asp.net-mvc asp.net-web-api

我为Webapi动作方法编写了一个过滤器。

public void OnActionExecuting(HttpActionContext actionContext)
{
      //Log area name here by calling the helper method.
    var areaNam = Helpers.GetAreaName(actionContext);
}

我想通过编写一个好的辅助方法来检索区域名称。

 public static string GetAreaName(System.Web.Http.Controllers.HttpActionContext httpContext)
 {
     var areaName = string.Empty;
     var routeData = httpContext.ControllerContext.RouteData;
     if (routeData != null)
     {
         areaName = routeData.Route.DataTokens["area"] as string;
     }

     return areaName;
 }

areaName始终为空或空。

任何人都可以对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

您希望Values不是DataTokens

public static string GetAreaName(System.Web.Http.Controllers.HttpActionContext httpContext)
{
    var areaName = string.Empty;
    var routeData = httpContext.ControllerContext.RouteData;
    if (routeData != null)
    {
        areaName = routeData.Route.Values["area"] as string;
    }
    return areaName;
}

Documentation - RouteData.Values

  

获取路由的URL参数值和默认值的集合。