我有一个Net Core MVC项目,在其中我使用用户身份,注册,登录等。
我的问题是,当我登录时,我将其重定向到文章索引,我想让用户使用await _userManager.GetUserAsync (User)
登录,但返回null
。
我向您展示了部分代码(如果您需要查看更多内容,请告诉我)。
LoginController
// is called when press submit button in register
public async Task<string> RegisterUser(RegisterViewModel model)
{
try
{
ErrorViewModel message = new ErrorViewModel();
bool x = await _roleManager.RoleExistsAsync("Customer");
if (!x)
{
var role = new IdentityRole
{
Name = "Customer"
};
await _roleManager.CreateAsync(role);
}
User user = new User
{
UserName = model.Email,
Name = model.Name,
Surname = model.Surname,
PhoneNumber = model.Phone,
Email = model.Email,
Address = model.Address,
LockoutEnabled = true,
LockoutEnd = DateTime.Now.AddYears(10)
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var result1 = await _userManager.AddToRoleAsync(user, "Customer");
return "Ok";
}
else
{
if (result.Errors.First().Code.Equals("PasswordRequiresLower"))
{
message.ErrorMsg = "La clave debe contener al menos una letra.";
return "Clave incorrecta";
}
message.ErrorMsg = "El email ingresado ya esta registrado en el sistema.";
return "Email incorrecto";
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "Error";
}
}
// is called when press submit button in login
public string LogInUser(LoginViewModel model)
{
if (_userDataAccess.Exist(model.Username))
{
User user = _userManager.FindByEmailAsync(model.Username).GetAwaiter().GetResult();
if (user == null)
user = _userManager.FindByNameAsync(model.Username).GetAwaiter().GetResult();
if (!user.LockoutEnabled && user.AccessFailedCount < 10)
{
_userManager.ResetAccessFailedCountAsync(user).GetAwaiter().GetResult();
_userManager.SetLockoutEnabledAsync(user, false).GetAwaiter().GetResult();
_userManager.SetLockoutEndDateAsync(user, DateTime.Now.AddDays(365)).GetAwaiter().GetResult();
}
else if (user.LockoutEnabled)
{
return "Su cuenta esta desactivada.";
}
var result = _signInManager.PasswordSignInAsync(user, model.Password, true, lockoutOnFailure: true).GetAwaiter().GetResult();
if (!_userManager.IsEmailConfirmedAsync(user).GetAwaiter().GetResult())
{
if (result.Succeeded)
{
if (user.AccessFailedCount > 0)
{
_userManager.ResetAccessFailedCountAsync(user).GetAwaiter().GetResult();
_userManager.SetLockoutEnabledAsync(user, false).GetAwaiter().GetResult();
}
return "Ok";
}
else if (result.IsLockedOut)
{
return "Su cuenta esta desactivada.";
}
else
{
return "Incorrecto";
}
}
else
{
return "El usuario no ha confirmado la cuenta";
}
}
else
return "El nombre de usuario es incorrecto";
}
ArticuloController
public async Task<IActionResult> Index()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
// here after successful login, user is null
List<Articulo> list = _articuloDataAccess.GetAll();
return View(list);
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddEntityFrameworkSqlServer().AddDbContext<MuebleriaDBContext>();
services.AddIdentity<User, IdentityRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<MuebleriaDBContext>()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}