Asp.net 提高自定义授权操作筛选器的性能
我已经创建了自己的自定义授权操作筛选器,如下所示:-Asp.net 提高自定义授权操作筛选器的性能,asp.net,entity-framework,asp.net-mvc-4,web-config,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(ActionExecutingC
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.
因此,在我的repository方法中,将对数据库进行两次点击,一次是获取int size的值,另一次是构建var securityrole。由于此方法将在执行web应用程序中的任何操作方法之前被调用,因此提高性能至关重要。
因此,我考虑将大小的值存储在我的web.confoge文件中,而不是查询数据库以检索此值,因为有四个权限级别(无、读取、编辑和删除),因此我将在我的web.config中拥有以下内容:-
<add key="none" value="0" />
<add key="edit" value="1" />
那么,如果我将四个权限级别存储在web.config中而不是存储在DB中,是否是提高性能的有效方法,有人能给出建议吗?
谢谢从性能的角度来看,我可能更关心第二个查询,它看起来效率不高,而不是它两次访问数据库。我会看看用户可以保留什么样的信息,并利用这些信息来存储这些信息。这是一个例子。例如,从查询中可以看出,您可以存储用户角色和组,这样就不需要每次都查找这些角色和组 操作的权限大小是否需要可配置,或者在应用程序生命周期中它们是否真的是静态的。如果它们不太可能更改,我将使用枚举类型来表示您的操作,可以这样表示:
public enum Actions : int
{
none = 0,
edit = 1
};
其中,整数值是权限大小。这消除了使用魔术字符串和另一个数据库查询。感谢您的回复,我以前没有使用基于声明的标识,目前我们已经实现了当前的自定义授权。我知道我的方法不是最好的,但没有什么是完美的。那么,为什么选择使用枚举类型,而不是在web.config文件中添加权限大小呢?当web.config缓存在内存中时,您仍然在XML文档中搜索以获取值。枚举类型是直接内存访问,它消除了那些在运行时才发现问题的讨厌的魔术字符串。
public enum Actions : int
{
none = 0,
edit = 1
};