Getting area, controller and action names inside filter attributes

拈花ヽ惹草 提交于 2019-12-05 21:52:31

When an area is registered the MapRoute method used is adding a dataContextToken to each route. You can check the source code here, you will see a method like the following and you will notice a line adding the data token:

public Route MapRoute(string name, string url, object defaults, object constraints, string[] namespaces)
{
    ...   
    route.DataTokens[RouteDataTokenKeys.Area] = AreaName;
    ...
    return route;
}

So in your filter you just need to get the data token with key "area" instead of a route value. For example the following filter will add a header the area, controller, and action found in the route

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var routingValues = filterContext.RouteData.Values;
    var currentArea = filterContext.RouteData.DataTokens["area"] ?? string.Empty;
    var currentController = (string)routingValues["controller"] ?? string.Empty;
    var currentAction = (string)routingValues["action"] ?? string.Empty;

    filterContext.HttpContext.Response.AddHeader("Routing info", string.Format("controller={0},action={1},area={2}", currentController, currentAction, currentArea));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!