Monday, July 21, 2014

C# AspNet Membership IsInRole - Save Roles To Session

// The purpose of the following Methods is to reduce the number of database calls and traffic bandwidth. // The following Method is used for verifying roles of another user, (NOT the contextual user) via administration site page.
public static bool IsInRole( string username, string rolename)
{
  string UserRolesCheck = "UserRolesCheck" + username;             if (HttpContext.Current.Session[UserRolesCheck] == null)             

{                 if (HttpContext.Current.Session[UserRolesCheck] == null)                 {                     string[] userRoles = System.Web.Security.Roles.GetRolesForUser(username);                     HttpContext.Current.Session[UserRolesCheck] = string.Join(",", userRoles);                 }             }             if (HttpContext.Current.Session[UserRolesCheck] != null)             {                 return ((String)HttpContext.Current.Session[UserRolesCheck]).Contains(rolename) ? true : false;             }             return false;         }    
// The following Method is used for verifying roles of current user.
The contextual user must be authenticated.

public static bool IsInRole(string rolename)         {             if (HttpContext.Current.Session["UserRoles"] == null)             {                 string[] userRoles = System.Web.Security.Roles.GetRolesForUser(System.Web.Security.Membership.GetUser().UserName);                 HttpContext.Current.Session["UserRoles"] = string.Join(",", userRoles);                                  if (HttpContext.Current.Session["UserRolesCheck"] != null)                         HttpContext.Current.Session["UserRolesCheck"] = null;             }             if (HttpContext.Current.Session["UserRoles"] != null)             {                 return ((String)HttpContext.Current.Session["UserRoles"]).Contains(rolename) ? true : false;             }             return false;         }         

No comments:

Post a Comment