User.IsInRole在ASP.NET Core(已实现存储库模式)中不返回任何内容 [英] User.IsInRole returns nothing in ASP.NET Core (Repository Pattern implemented)

查看:224
本文介绍了User.IsInRole在ASP.NET Core(已实现存储库模式)中不返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下配置的ASP.NET Core(完整.NET Framework)应用程序:

I have an ASP.NET Core (Full .NET Framework) application with the following configuration:

Startup.cs

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

The ApplicationUser extends from IdentityUser and ApplicationDbContext extends 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>>());
    }
}

这是我的演示数据:

角色表

用户表

UserRole表

在我的登录操作中,我有以下内容:

In my Login Action i have the following:

[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);
}

我要实现的是登录后将用户重定向到特定区域.

What i want to achieve is to redirect the user to a certain area after login.

我当前面临的问题是函数User.IsInRole("Admin")返回false,并且在调试模式下,如果我查看usermanager,则当前用户没有加载角色(计数= 0).

The current problem i'm facing is that the function User.IsInRole("Admin") returns false and in debug mode, if i look at the usermanager, the current user doesn't have the roles loaded (Count = 0).

任何想法都会受到赞赏.

Any thoughts would be appreciated.

更新1

忽略角色ID"原因是错误的.实际上,用户已映射了正确的值.

Ignore the Role Id cause is wrong. In fact the user is mapped with the correct value.

推荐答案

User.IsInRole正在检查cookie.但是,您正在登录时在同一http请求中检查此内容. Cookie根本不存在-在答复或下一个请求中将可用.

User.IsInRole is checking the cookie. But you are checking this within the same http request as you sign-in. Cookie is simply not there yet - it will be available on the reply or next request.

此时,您需要使用ApplicationUserManager.IsInRoleAsync(TKey userId, string role)来检查数据库.

At that point you need to use ApplicationUserManager.IsInRoleAsync(TKey userId, string role) to check against the database.

这篇关于User.IsInRole在ASP.NET Core(已实现存储库模式)中不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆