User.IsInRole ничего не возвращает в ASP.NET Core (реализован шаблон репозитория)
У меня есть приложение ASP.NET Core (Full .NET Framework) со следующей конфигурацией:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(p => {
p.Password.RequireDigit = true;
p.Password.RequireNonAlphanumeric = false;
p.Password.RequireUppercase = true;
p.Password.RequiredLength = 5;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<IDbFactory, DbFactory>();
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddTransient<IUserRepository, UserRepository>();
services.AddTransient<IUserService, UserService>();
}
ApplicationUser расширяется от IdentityUser, а ApplicationDbContext расширяет IdentityDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public virtual void Commit()
{
base.SaveChanges();
}
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
base.OnConfiguring(builder);
builder.UseSqlServer("connection string here");
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
// Configure model
// Identity
new Configuration.Identity.ApplicationUserConfiguration(builder.Entity<ApplicationUser>());
new Configuration.Identity.ApplicationUserProfileConfiguration(builder.Entity<ApplicationUserProfile>());
new Configuration.Identity.RoleConfiguration(builder.Entity<IdentityRole>());
new Configuration.Identity.RoleClaimConfiguration(builder.Entity<IdentityRoleClaim<string>>());
new Configuration.Identity.ApplicationUserRoleConfiguration(builder.Entity<IdentityUserRole<string>>());
new Configuration.Identity.ApplicationUserClaimConfiguration(builder.Entity<IdentityUserClaim<string>>());
new Configuration.Identity.ApplicationUserLoginConfiguration(builder.Entity<IdentityUserLogin<string>>());
new Configuration.Identity.ApplicationUserTokenConfiguration(builder.Entity<IdentityUserToken<string>>());
}
}
Вот мои демонстрационные данные:
Ролевая таблица
Таблица пользователей
Таблица пользовательских ролей
В моем действии входа в систему у меня есть следующее:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
if (User.IsInRole("Admin"))
{
return RedirectToAction("Index", "Home", new { area = "Admin" });
}
return RedirectToAction("Index", "Home");
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Чего я хочу добиться - это перенаправить пользователя в определенную область после входа в систему.
Текущая проблема, с которой я сталкиваюсь, заключается в том, что функцияUser.IsInRole("Admin")
возвращает false и в режиме отладки, если я смотрю на usermanager, у текущего пользователя нет загруженных ролей (Count = 0).
Любые мысли будут оценены.
Обновление 1
Проигнорируйте Идентификатор роли, причина неправильна. На самом деле пользователь отображается с правильным значением.