How can I check if a user is in any one of a few different roles with MVC4 Simple membership?

后端 未结 8 816
日久生厌
日久生厌 2020-12-04 17:47

I understand that a good way to check if an user is in a role is:

if (User.IsInRole(\"Admin\"))
{

}

However How can I check if my user is

8条回答
  •  既然无缘
    2020-12-04 18:27

    I used the below code. In my case, I had a semi colon de-limited string as the parameter which is read from web.config. You may change the below code easily if you are passing a List.

    public class ActiveDirectoryGroup
    {
        public static bool IsInAnyRole(string adRoles)
        {
            return adRoles.Split(Convert.ToChar(";")).Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
            //If list is passed use below
            //return listParameter.Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
        }
    }
    

    In web.config:

    
      
    
    

    I used it like below in my page load:

    if (ActiveDirectoryGroup.IsInAnyRole(ConfigurationManager.AppSettings["ADGroup"]))
    {
      //do something
    }
    

提交回复
热议问题