获取ActionName,ControllerName和AreaName,并在ActionFilter Attribute中传递它

Sae*_*eid 35 asp.net-mvc authorization authorize-attribute action-filter asp.net-mvc-3

我使用自定义AuthorizationFilter,如下所示:

public class ActionAuthorizeAttribute : AuthorizeAttribute {

protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) {

        if(!httpContext.User.Identity.IsAuthenticated)
            return false;

        if(IsUserExcluded())
            return false;
        else
            return IsRoleAuthorize(httpContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在每个操作的顶部使用此过滤器,并且要检查是否已授权,需要操作名称,控制器名称和区域名称.那么有没有办法在AuthorizeCore()使用方法中获得这些名称System.Web.HttpContextBase?如果答案是否,那么我怎么能得到这个名字并将其传递给属性,显然我不想手工添加每个名字,实际上就像ViewContext.RouteData.Values["Controller"]在控制器中一样:

[ActionAuthorize(actionName=Action, controller=ControllerName, area=AreaName)]
public ActionResult Index() {
    return View();
}
Run Code Online (Sandbox Code Playgroud)

有人对此有任何想法吗?

Dar*_*rov 83

您可以从RouteData获取它们:

protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
    var rd = httpContext.Request.RequestContext.RouteData;
    string currentAction = rd.GetRequiredString("action");
    string currentController = rd.GetRequiredString("controller");
    string currentArea = rd.Values["area"] as string;

    ...

}
Run Code Online (Sandbox Code Playgroud)

  • 这可能只是在ASP.NET MVC 4中,但该区域位于rd.DataTokens ["area"]中. (11认同)
  • @AndersM.,我宁愿不这样做.这将使我的代码非常单元测试不友好.我总是喜欢使用抽象.不记得我职业生涯中上次使用`HttpContext.Current`的时间. (5认同)