Something that isn't support by default in asp.net is the ability to have end users login using either their username or their email address. Though it is somewhat easy to add this support using this little trick to override the normal login procedure on the login control.

To get started we will need our aspx page with a login control as follows.

<asp:Login runat="server" ID="Login2" DisplayRememberMe="false"
    DestinationPageUrl="/Users/Default.aspx" onloggingin="Login2_LoggingIn" >
</asp:Login>

We can then override the default action in the event handler if we cannot find the current user trying to login and the username contains an '@' symbol.

public partial class Login : AppPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Login2_LoggingIn(object sender, LoginCancelEventArgs e)
    {
        if (Login2.UserName.Contains("@") && Membership.GetUser(Login2.UserName) == null)
        {
            string Username = Membership.GetUserNameByEmail(Login2.UserName);
            if (Username == null)
                return;

            if (Membership.ValidateUser(Username, Login2.Password) == true)
            {
                FormsAuthentication.SetAuthCookie(Username, false); 
                FormsAuthentication.RedirectFromLoginPage(Username, false);
                e.Cancel = true;
            }
        }
    }
}

Note: if you are going to use the above you will need to make sure that your configured provider has a unique set of email addresses per user.





Last Modified: 20 February 2017

Releated Posts


2011-10-27 - CSharp - Number Of Cores and Processors
2011-10-04 - CSharp - Thread Queue Example
2011-09-29 - CSharp - Background Thread / Task
2011-09-17 - CSharp - Lookup Hostname
2011-08-29 - CSharp - IsGuid
2011-08-29 - C Sharp - StopWatch, The high resolution timer
2011-08-26 - CSharp - Convert Between Meters and Feet
2011-08-23 - CSharp - ThreadPool and Windows Forms
2011-08-10 - C Sharp - MD5Sum / SHASum
2011-07-22 - CSharp - Fibonacci sum
2011-07-13 - CSharp - Palindrome
2011-07-11 - CSharp - The string Reverse
2011-07-10 - CSharp - Interviews FizzBuzz
2011-06-27 - CSharp - HowTo Parse a URL
2011-06-22 - CSharp - Extending any class
2011-06-13 - ASPNET - Login by username or email
2011-05-22 - MSSQL - Removing the aspnet membership database
2011-05-12 - CSharp - ASPNET Logoff
2011-03-07 - C Sharp - Windows Logoff
2011-03-02 - ASPNET - Dynamic Controls
2011-03-01 - C Sharp - Resize an image by size of height
2011-02-23 - C Sharp / MSSQL Get inserted value of NEWSEQUENTIALID()
2011-02-10 - CSharp - Wake on Lan (WOL) Packet
2011-02-10 - CSharp - Shutdown or reboot windows
2011-02-06 - C Sharp - Gridview Bound Yes No
2011-02-05 - MSSQL - Levenshtein
2011-01-30 - MSSQL - Enabling CLR Functions
2011-01-30 - MSSQL - Adding MD5 checksum support
2011-01-30 - MSSQL - RegEx Support
2011-01-30 - MSSQL - Adding SHASum support