【发布时间】:2012-07-09 08:10:47
【问题描述】:
我在我的 ASP.NET 应用程序中有角色。我已经解决了问题(我认为)。应用程序中的每个页面都使用角色和权限的问题。因此它在页面加载中使用了以下函数
if (Roles.IsUserInRole("Admin")) { // 显示页面 } 别的 { // 不 }
我从这个问题Poor Performance with WindowsTokenRoleProvider找到了我的问题的解决方案
但是有一些不同之处 1.以上问题使用WindowsTokenRoleProvider,我使用的是SqlRoleProvider
由于上述问题,上述解决方案并不完全适合我。
到目前为止我所做的,并且我部分成功,我从 SqlRoleProvider 派生了一个类,并包含了这个与上述问题相同但经过修改的函数。我更改了 web.config,使其看起来像这样
<roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPR0L3S" cookieTimeout="117" cookieSlidingExpiration="true" cookieProtection="All" createPersistentCookie="false" defaultProvider="CustomSqlRoleProvider">
<providers>
<add name="CustomizedRoleProvider" type="CustomSqlRoleProvider" connectionStringName="PEGConn" applicationName="/CRM"/>
</providers>
</roleManager>
这是我类中的函数,它确实得到(仅在用户登录时执行)
public override string[] GetRolesForUser(string username)
{
// Will contain the list of roles that the user is a member of
List<string> roles = null;
// Create unique cache key for the user
string key = String.Concat(username, ":", base.ApplicationName);
// Get cache for current session
Cache cache = HttpContext.Current.Cache;
// Obtain cached roles for the user
if (cache[key] != null)
{
roles = new List<string>(cache[key] as string[]);
}
// Was the list of roles for the user in the cache?
if (roles == null)
{
string[] AllRoles = GetAllRoles();
roles = new List<string>();
// For each system role, determine if the user is a member of that role
foreach (String role in AllRoles)
{
if (base.IsUserInRole(username, role))
{
roles.Add(role);
}
}
// Cache the roles for 1 hour
cache.Insert(key, roles.ToArray(), null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
// Return list of roles for the user
return roles.ToArray();
}
问题是当 Roles.IsUserInRole 函数调用相同的旧时
System.Web.Security.Roles.IsUserInRole
功能。我什至在我的新类中重载了这个函数,但它永远不会被执行。我基本上缓存了所有角色,以便在每个页面刷新时应用程序不会从一开始就搜索所有角色。
我需要从System.Web.Security.Roles.IsUserInRole 派生另一个类吗?有人做过吗?
每页刷新大约需要 4-8 秒,这太长了。代码在 VS 2008 中,C# 3.5
【问题讨论】:
-
你确定是这个问题吗?您是否尝试过取消角色检查并为您的应用程序计时?
-
为什么要显式调用 base.IsUserInRole(username, role) ?这将始终调用基类实现。如果您在派生类上实现了 IsUserInRole,请改为调用它!您是否对您的应用进行了分析以确定哪种方法花费的时间最多?
-
你确定这真的是问题吗?我有很多检查安全性的页面,加载它们不需要 4 到 8 秒。这应该是一个数据库查询,最大值。这不应该需要 4 秒。在为此付出很多努力之前,我会尝试注释掉您的安全检查,这样您就可以确定它需要 0 时间,并查看页面加载速度。
-
我确实分析了我的应用程序,并且一直在这里花费的时间最多。禁用它会使其相当快。但我可以仔细检查。不久前做过。
-
@dash 这是我的问题。在每个页面上使用
using System.Web.Security;,我应该将其更改为我自己的自定义类文件名吗?这是我需要帮助的地方。