How to make WebSecurity.Login to login using username or email?

后端 未结 4 2161
礼貌的吻别
礼貌的吻别 2020-12-13 04:45

WebSecurity.Login in simplemembership take username and password, how to make it to login the user using username or email instead of just username?, to make th

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 05:40

    You could inherit from the SimpleMembershipProvider and just override the ValidateUser method like this.

    public class ExtendedSimpleMembershipProvider : SimpleMembershipProvider
    {
        public override bool ValidateUser(string login, string password)
        {
            // check to see if the login passed is an email address
            if (IsValidEmail(login))
            {
                string actualUsername = base.GetUserNameByEmail(login);
                return base.ValidateUser(actualUsername, password);
            }
            else
            {
                return base.ValidateUser(login, password);
            }
    
        }
    
        bool IsValidEmail(string strIn)
        {
            // Return true if strIn is in valid e-mail format.
            return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }
    
    }
    

    This is just one approach. You could write your own MembershipProvider but if you only need to change the ValidateUser method this should work.

    Add the following configuration to the web.config to setup the provider.

         
        
        
        
        
      
    

    That should get you going in the right direction.

提交回复
热议问题