开发者

Get area name from ActionExecutingContext

I'm writing an ActionFilter and need to get area name from Ac开发者_如何学运维tionExecutingContext parameter (I want to implement quick-and-dirty login based security). Is it possible?


Usage

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

Code

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


From MVC Sourcecode:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜