支持在ASP.NET Core中使用同一用户的电子邮件或用户名登录 [英] Support login with email or username for same user in ASP.NET Core
问题描述
我正在将ASP.NET Core Identity(2.0)与所有默认代码一起使用.我更改了 AccountController.Login
方法以检查旧数据库并在找不到用户时迁移用户.由于该旧数据库同时具有用户名和电子邮件,因此我将在新创建的用户中填充这两个字段.
I'm using ASP.NET Core Identity (2.0) with all the default code. I changed the AccountController.Login
method to check a legacy database and migrate users when a user is not found. Since that old database had both usernames and emails, I'm populating both fields in the newly created user.
但是,如果我尝试使用迁移的用户再次登录,则无法使用电子邮件,因为似乎SQL请求总是在 W.E u.NormalizedUserName = @__ normalizedUserName_0
中查找
But then, if I try to log in again with a migrated user, using the email doesn't work, as it seems the SQL request always look for WHERE u.NormalizedUserName = @__normalizedUserName_0
only.
如何为单个用户提供一封电子邮件和一个不同的用户名,以使用他们的用户名或电子邮件登录?
How can I enable a single user with an email and a username that differ to log in with either their username or their email?
推荐答案
您可以使用 UserManager
中的 CheckPasswordAsync(user,password)
方法:> https://github.com/aspnet/Identity/blob/a273e349eea2be3a40b2b95bsrc/Core/UserManager.cs#L692
You have the possibility to use CheckPasswordAsync(user, password)
method from UserManager
: https://github.com/aspnet/Identity/blob/a273e349eea2be3a40b16e6947b2deab95f4b5b2/src/Core/UserManager.cs#L692
在调用该方法之前,您可以通过以下方式获取用户:
Right before calling that method you can fetch your user in the following manner:
var user = await _userManager.FindByNameAsync(userName) ?? await _userManager.FindByEmailAsync(userName);
根据您当前的 UserStore
实现,您可能需要调整 FindByNameAsync
或 FindByEmailAsync
或两者.
Based on your current UserStore
implementation you may need to adjust FindByNameAsync
or FindByEmailAsync
or both.
这篇关于支持在ASP.NET Core中使用同一用户的电子邮件或用户名登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!