Cute babysnake
Cute babysnake

Reputation: 61

IsInRole as Administrator is not validated true

I would like to redirect login users to admin page if they are administrators as follows,

            if (User.IsInRole("Administrator"))
            {
                return RedirectToAction("AdminLayout", "Home");
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }

But else's return is always performed.

In the database i have inserted a user "admin" with UserId=1 password "admin"

and in roles table I have RoleId=1 and RoleName=Administrator

and in UsersInRoles table I have RoleId=1 and UserId=1

Update

In web.config,

   <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
        <providers>
        <clear/>
        <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
      </providers>
    </roleManager>

Upvotes: 1

Views: 142

Answers (1)

Michael Richardson
Michael Richardson

Reputation: 4282

When are you attempting the redirect? If it's before the next page load the User object won't yet be resolved. Set a breakpoint in your code and I think you'll discover that User is null. Of course, null will never be in the Administrator role.

To work around this you can

  1. Do the redirect on the next page

    OR

  2. Grab the username from the login process then find the user logging in and check the role.

Upvotes: 1

Related Questions