我想知道是否有一個更有效的路線來採取。使用AspNet.Identity
我希望允許用戶使用他們的UserName
或Email
登錄到同一個文本框。我繼續在AccountController Login ActionResult
中解決這個問題。我打電話之前運行檢查:允許用戶使用電子郵件或用戶名(AspNet.Identity)登錄
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true);
的檢查:
//TODO: determine if there is a more efficient way to allow user to login either with Email || UserName
if (model.UserName.Contains("@"))
{
using (var context = new ApplicationDbContext())
{
model.UserName = (context.Users.Any(p => p.Email == model.UserName)) ?
context.Users.SingleOrDefault(p => p.Email == model.UserName).UserName :
model.UserName;
}
}
我在這裏的擔憂有兩個方面:
- 是他們這樣做更有效的可行之路。
- 我是否以這種方式引入了新的安全風險或性能風險?
我包括下面的整個
ActionResult
參考。
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
//TODO: determine if there is a more efficient way to allow user to login either with Email || UserName
if (model.UserName.Contains("@"))
{
using (var context = new ApplicationDbContext())
{
model.UserName = (context.Users.Any(p => p.Email == model.UserName)) ?
context.Users.SingleOrDefault(p => p.Email == model.UserName).UserName :
model.UserName;
}
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
您可以先不檢查條目是否具有「@」。 – 2014-09-24 05:35:36
@RedSerpent我檢查該條目是否具有「@」的原因是因爲如果我不需要,我不想用'context.Users.Any' LINQ查詢命中數據庫。碰到數據庫會是一個更好的解決方案嗎?你有什麼問題來檢查'@'? – aaronmallen 2014-09-24 05:39:50
當我以Identity 1.0開頭時,我遇到了同樣的問題,我不得不同時插入email和userName字段。 – DSR 2014-09-24 08:27:35