C3rd
Use Email as Username with ASP.NET Membership
Posted: 27 Dec 2012, 5:16am - ThursdayCouple of guides in the internet on using email as username with the ASP.NET Membership but the guide is too long and its a maze and crazy as hell for me. I found my own answer as simple as I wanted to. In my case, I created my own form. Form (View):
<form action="/home/authenticate" method="post" name="login"> <label>Email</label> <input type="text" name="email" /> <br class="clear" /> <label>Password</label> <input type="password" name="passwd" /> <br class="clear" /> <input type="submit" name="submit" value="Login" /> </form>Authentication (Controller):
[HttpPost] public ActionResult Authenticate() { Regex regex_email = new Regex(@"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"); var email = Request.Form["email"]; var passwd = Request.Form["passwd"].Trim(); if ((!regex_email.IsMatch(email)) || (passwd.Length < 6)) { return RedirectToAction("Index", "Home", new { msg = "Invalid username or password!" }); } else { string username = Membership.GetUserNameByEmail(email); if (Membership.ValidateUser(username, passwd)) { FormsAuthentication.SetAuthCookie(username, true); return RedirectToAction("Index", "Project"); } else { return RedirectToAction("Index", "Home", new { msg = "Invalid username or password!" }); } } }I just call the Membership.GetUserNameByEmail() then validate with Membership.ValidateUser(). That's it! Hope this help to others too.. :)