Why does IsInRole always return false?

為{幸葍}努か 提交于 2019-12-17 20:43:19

问题


I am building an MVC5 application with ASP.NET Identity 2.0 and EF 6.1.1.

This is part of my current Login method:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
            return View(model);

        var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true);
        switch (result)
        {
            case SignInStatus.Success:
                {
                    var user = await UserManager.FindAsync(model.UserName, model.Password);

                    if (user == null)
                        break;

                    if (!UserManager.IsInRole(user.Id, "OfficeUser"))
                        break; // << I always hit this line - even if the user is an OfficeUser

This works fine until I hit UserManager.IsInRole(). This always returns false.

Somewhere I read that IsInRole() will fail if the corresponding user is not signed in. But since I pass SignInManager.PasswordSignInAsync() I believe this should be fine.

And yes, I have checked the database many times and very carefully ;) My test user and my test role "OfficeUser" are definitely assigned to each other.

Does anybody have an idea?


回答1:


I had same kind of issue, then I got work it as below. The reason seems to be, the user not completely signin or completed all authentication process in this stage.

case SignInStatus.Success:
                {
                    var user = await UserManager.FindAsync(model.UserName, model.Password);
                    var roles = await UserManager.GetRolesAsync(user.Id)

                    if (user == null)
                        break;

                    if (roles.Contains("OfficeUser"))
                        break; // << I always hit this line - even if the user is an OfficeUser


来源:https://stackoverflow.com/questions/26273598/why-does-isinrole-always-return-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!