1

我目前正在研究过滤器 [Authorize] 的扩展,以便我可以从数据库中检索权限。一切正常,但这肯定是一个性能问题。每次我向数据库发送查询请求权限时,这都不是确定这一点的最佳方法。所以我想把这些数据放在Session中。将数据从数据库放入 Session 对象的最快方法是什么,我可以问(LINQ)以及数据库。

现在看起来像:

var _allowedRolesDB = context.sec_RolesInCAs
                .Where(rl => rl.MenuControlName == controllRights && rl.MenuActionName == actionRights)
                .Select(rl => rl.RoleName);

            foreach (var r in _allowedRolesDB)
            {
                RolesDB = RolesDB + r.ToString() + ",";
            }

但我想改成

var _allowedRolesDB = MySuperSessionSomethink
.Where(rl => rl.MenuControlName == controllRights && rl.MenuActionName == actionRights)
                .Select(rl => rl.RoleName);

            foreach (var r in _allowedRolesDB)
            {
                RolesDB = RolesDB + r.ToString() + ",";
            }

MySuperSessionSomethink 将保留从数据库中一次性检索到的数据。知道我该怎么做吗?Tx 寻求帮助。


更大的图景

好的。我将展示更大的画面。整个想法是创建自定义授权过滤器。

    [CustomAuthAttribute("Home,Index", Roles = "SuperAdministrator")]
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

这是什么目标。创建具有所有优点的授权属性,以及其他功能,例如在数据库中保留有关权限的信息。

现在我要做的是:

public CustomAuthAttribute(params string[] controllerAction)
{
        IPrincipal user = HttpContext.Current.User;
        string userName = user.Identity.Name;
        **... some code .. and take all allowed roles and check it have permissions** 
        var _allowedRolesDB = context.sec_RolesInCAs
            .Where(rl => rl.MenuControlName == controllRights && rl.MenuActionName == actionRights)
            .Select(rl => rl.RoleName);

        foreach (var r in _allowedRolesDB)
        {
            RolesDB = RolesDB + r.ToString() + ",";
        }
        **... some code .. thesame withs single users**

}

在此之后我使用

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
   **... can acces or not part of code ...**
   if (_rolesSplit.Any(user.IsInRole))
   {
        return true;
    }
}

但是有问题。每次我向数据库询问权限时,恕我直言,这不是最好的方法。现在我的想法是获取一个用户的所有权限,并在他被授权时将他放入他的会话中。也许我错了,这种方式会产生问题,但是保留在数据库中并一直询问权限也不是一个好主意:)。那么,在对数据库提出一两个问题之后,也许更好的方式来获取数据并在代码中使用?

4

1 回答 1

0

首先,您似乎希望将这些添加到缓存中,而不是会话中。它们对应用程序来说似乎是全局的,而不是特定于用户的。由于您正在通过菜单控件/操作查找角色,因此我只需将它们添加到缓存中作为查找:

string action = controlRights + actionRights;
string allowedRoles = Cache[action];
if (allowedRoles == null) 
{
    allowedRoles = String.Join(",", context.sec_RolesInCAs
        .Where(rl => rl.MenuControlName == controlRights && rl.MenuActionName == actionRights)
        .Select(rl => rl.RoleName)
        .ToArray());
    Cache[action] = allowedRoles;
}

这将从第二个请求的缓存中为您提供给定控制/操作的允许角色。

于 2012-03-19T10:57:40.697 回答