提高自定义授权操作筛选器的性能

时间:2013-11-18 09:55:48

标签: asp.net entity-framework asp.net-mvc-4 web-config

我创建了自己的自定义授权操作过滤器,如下所示: -

public class CheckUserPermissionsAttribute : ActionFilterAttribute
    {

        public string Model { get; set; }
        public string Action { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // var user = User.Identity.Name; // or get from DB  
            Repository repository = new Repository();
            string ADusername = filterContext.HttpContext.User.Identity.Name.Substring(filterContext.HttpContext.User.Identity.Name.IndexOf("\\") + 1);
            if (!repository.can(ADusername,Model,Action)) // implement this method based on your tables and logic
//code goes here.

调用以下存储库方法: -

public bool can(string user, string Model, string Action)

int size = tms.PermisionLevels.Where(a5 => a5.Name == Action).SingleOrDefault().PermisionSize;

var securityrole = tms.SecurityroleTypePermisions.Any(a => a.PermisionLevel.PermisionSize >= size 
    && (a.TechnologyType.Name == Model || Model == "All") 
    && (a.SecurityRole.SecurityRoleUsers.Any(a2 => a2.UserName.ToLower() == user.ToLower()) || a.SecurityRole.Groups.Any(a3 => a3.TMSUserGroups.Any(a2 => a2.UserName.ToLower() == user.ToLower()))));
//code goes here.

因此,在我的存储库方法中,数据库会有两次命中,一次获取int大小的值,另一次获取var securityrole。并且在执行Web应用程序中的任何操作方法之前将调用此方法,因此提高性能至关重要。 所以我想在我的web.confoge文件中存储大小的值而不是查询数据库来检索它,因为有四个权限级别(无,读取,编辑和删除)所以我会有一些内容,如内部我的web.config: -

 <add key="none" value="0" />
  <add key="edit" value="1" />

我的演绎方法看起来就像我现在的代码一样: -

public bool can(string user, string Model, string Action)

int size = System.Web.Configuration.WebConfigurationManager.AppSettings[Action];

如果我在web.config中而不是在DB内部存储四个权限级别的方法是一种提高性能的有效方法,那么任何人都可以建议吗? 感谢

1 个答案:

答案 0 :(得分:1)

从性能的角度来看,我可能会更关心第二个查询,它看起来效率不高,而不是两次查询数据库。我会看一下用户可以保留哪些信息,并利用claims-based identity来存储这些信息的信息。这是一个article that shows how to get increased performance during authorization using claims。例如,从您的查询中可以看出,您可以存储用户角色和组,这样就不需要每次都查找。

操作的权限大小是否需要可配置,或者它们在应用程序生命周期中是否真的是静态的。如果他们不太可能改变,我会使用枚举类型来表示你的行为,这可以表示如下:

public enum Actions : int
{
    none = 0,
    edit = 1
};

整数值是权限大小。这消除了使用魔术字符串和其他数据库查询。