美好的一天,请我正在编写一个MVC应用程序,该应用程序只能允许用户使用ID,电子邮件和密码三个参数登录。我的问题是PasswordSignInAsync有两个主要参数电子邮件和密码。如何覆盖它以允许 ID 作为登录的另一个参数。
这是普通代码:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// 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.Email,model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToAction("DealerDashboard", "Dealers");
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);
}
}
在我的解决方案中,我想这样做:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// 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.id,model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToAction("DealerDashboard", "Dealers");
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);
}
}
确实,正如伊戈尔所说,您只需要覆盖SignInManager
.像这样:
public class ApplicationSignInManager : SignInManager<ApplicationUser, Guid>
{
// adjust as needed
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public Task<SignInStatus> PasswordSignInAsync(string userId, string userName, string password, bool isPersistent, bool shouldLockout)
{
var user = await base.UserManager.FindByIdAsync(userId);
// do validation for user, etc.
return base.PasswordSignInAsync(userName, password, isPersistent, shouldLockout);
}
}