从 ActionExecutingContext 获取区域名称

Sib*_*Guy 4 asp.net-mvc

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

Ghe*_*wet 5

用法

@Html.Controller();
@Html.Action();
@Html.Id();
@Html.Area();
Run Code Online (Sandbox Code Playgroud)

代码

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;
    }
}
Run Code Online (Sandbox Code Playgroud)