Custom Membership and Role provider in ASP.NET MVC 4

后端 未结 4 1761
一个人的身影
一个人的身影 2020-12-05 07:43

I am creating an ASP.NET MVC 4 web application. I googled about custom membership, but I couldn\'t find good resources or video lectures.

Most of them are either out

4条回答
  •  感情败类
    2020-12-05 08:23

    http://logcorner.com/how-to-configure-custom-membership-and-role-provider-using-asp-net-mvc4/
    
    **for creating a CustomerMemberShipClass** your class must implement System.Web.Security.MembershipProvider abstarct class. and you override the method ValidateUser()
    in this ValidateUser() you have to write your own logic based on which you want authenticate user and return true or false according to it.
    
    Sample ValidateUser method 
      public override bool ValidateUser(string username, string password)
            {
               int count=db.GetAll().Where(x => x.UserEmail == username && x.password == password).Count();
               if (count != 0)
                   return true;
               else
                   return false;
            }
    
    later in web.config file you have add the fallowing under  element
    
    
    
          
            
            
          
        
    
    after doing this you can validate user using **MemberShip.Validate(Username,password)** which returns true or false based on ur code in ValidateUser() in CustomMemberShipProvider class and this will also set **[Authorize] attribute**
    
    **for creating a CustomRoleProviderClass** your class must inherit System.Web.Secuirty.RoleProvider and override the appropriate method to get the roles for the user
    
    SAmple method for getting roles for user
    
    
     public override string[] GetRolesForUser(string username)
            {
                string[] str={db.GetAll().Where(x=>x.UserEmail==username).FirstOrDefault().Role};
                return str;
            }
    
    after this you must add the fallowing in web.config file in  element
    
    
          
            
            
          
        
    
     and after this u can check the role of the user using attribute **[Authorize(role="admin"])** and in Razor view you can check using User.IsinROle("A").
    

提交回复
热议问题