My MVC application uses the user role in several places during separate page requests. My question is, does SqlRoleProvider cache the current user roles for the page request lifetime by default?
For example, I use Roles in attributes in controller methods:
[Authorize(Roles = "Admin")]
and custom code
if (user.IsInRole(MembershipRole.Admin)) { // Do something } else if (user.IsInRole(MembershipRole.Printer)) { // Do something else }
If the role provider does not cache roles, is the best solution for writing a custom role provider that inherits from the standard one and overrides the methods to get the Roles once and cache them for the duration of the Request? Can this be done so that both the Authorize attribute and my own code use cached roles?
(If you're interested, I don't want to use the cacheRolesInCookie web.config parameter to cache roles in cookies).
Thanks in advance for any suggestions.
[Edit to include details invoked from Joeβs response]
I decompiled System.Web.Mvc.AuthorizeAttribute and the AuthorizeCore method calls the following method for each role being checked:
httpContext.User.IsInRole
Then, peering into System.Web.Security.RolePrincipal (this is what the βUserβ is above), both methods below actually use a cached copy of the user roles (or populate the cache if they are empty):
public string[] GetRoles() public bool IsInRole(string role)
The cache is stored as a user field, so its lifetime is throughout the request.
Methods will find roles using:
Roles.Providers[this._ProviderName].GetRolesForUser(this.Identity.Name)
therefore, it will use any role provider that you have selected for the application (default or custom).