从ActionExecutingContext获取区域名称

时间:2011-07-28 16:31:55

标签: asp.net-mvc

我正在编写一个ActionFilter,需要从ActionExecutingContext参数获取区域名称(我想实现基于快速和脏的登录安全性)。有可能吗?

2 个答案:

答案 0 :(得分:3)

<强>用法

@Html.Controller();
@Html.Action();
@Html.Id();
@Html.Area();

<强>代码

public static class HtmlRequestHelper
{
    public static string Id(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("id"))
            return (string)routeValues["id"];
        else if (HttpContext.Current.Request.QueryString.AllKeys.Contains("id"))
            return HttpContext.Current.Request.QueryString["id"];

        return string.Empty;
    }

    public static string Controller(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("controller"))
            return (string)routeValues["controller"];

        return string.Empty;
    }

    public static string Action(this HtmlHelper htmlHelper)
    {
        var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

        if (routeValues.ContainsKey("action"))
            return (string)routeValues["action"];

        return string.Empty;
    }

    public static string Area(this HtmlHelper htmlHelper)
    {
        var dataTokens = HttpContext.Current.Request.RequestContext.RouteData.DataTokens;

        if (dataTokens.ContainsKey("area"))
            return (string)dataTokens["area"];

        return string.Empty;
    }
}

答案 1 :(得分:2)

来自MVC源代码:

    static string GetAreaName(RouteBase route)
    {
        var area = route as IRouteWithArea;
        if (area != null)
        {
            return area.Area;
        }
        var route2 = route as Route;
        if ((route2 != null) && (route2.DataTokens != null))
        {
            return (route2.DataTokens["area"] as string);
        }
        return null;
    }


    static string GetAreaName(RouteData routeData)
    {
        object obj2;
        if (routeData.DataTokens.TryGetValue("area", out obj2))
        {
            return (obj2 as string);
        }
        return GetAreaName(routeData.Route);
    }