I have roles on my ASP.NET application. I have figure the problem (I think). The problem every page in the applications uses role and permission. Therefore it uses the following function in page load
if (Roles.IsUserInRole("Admin")) { // display the page } else { // No }
I found a solution to my problem from this question Poor Performance with WindowsTokenRoleProvider
But there are a couple of differences 1. The above question uses WindowsTokenRoleProvider, I am using SqlRoleProvider
Because of the above problem, the above solution does not exactly work for me.
What I have done so far, and I am partially successful, I have derived a class from SqlRoleProvider and include this function which is the same from above question but modified. I changed web.config so that it looks like this
<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>
This is the function inside my class, which does get (executed only when a user login)
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();
}
The problem is when Roles.IsUserInRole function calls the same old
System.Web.Security.Roles.IsUserInRole
function. I have even overloaded this function in my new class but it never gets executed. I am basically caching all the roles so that on each page refresh the application does not go search for all roles right from the start.
Do I need to derive another class from System.Web.Security.Roles.IsUserInRole
? Has anyone done it.
Each page takes about 4-8 seconds on fresh which is too long. Code is in VS 2008, C# 3.5