问题
I have a register page where the user is assigned to a role as follows once the user clicks on the submit button:
MembershipUser oMU;
if (!(Roles.RoleExists("Stream")))
{
Roles.CreateRole("Stream");
}
oMU = Membership.CreateUser(txtUserName.Text.Trim(), txtPassword.Text.Trim(), txtEmail.Text.Trim());
Membership.UpdateUser(oMU);
Roles.AddUserToRole(oMU.UserName, "Stream");
When the user goes to a login screen, I have the following:
When the user logs in, I need to make sure that they indeed are part of that role:
if (User.IsInRole("Stream"))
{
}
but it never goes into the User.IsInRole block. What do I need to do in order to have the user who registered be part of the Role such that it works with User.IsInRole.
Note that I have a folder as such so I need them to be part of the Streaming Role:
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<deny users="*" />
<allow roles="Stream" />
</authorization>
</system.web>
</configuration>
回答1:
Move <allow roles="Stream" />
above <deny users="*" />
. Otherwise, all users will be denied.
<configuration>
<system.web>
<authorization>
<allow roles="Stream" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
Make sure to you have membership and RoleManager in web.config
Here is the sample -
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<clear/>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="XXXXXSqlConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="XXXXX"/>
</providers>
</membership>
<roleManager enabled="true" cacheRolesInCookie="false" defaultProvider="DefaultRoleProvider">
<providers>
<clear/>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="XXXXXSqlConnection" applicationName="XXXXX"/>
</providers>
</roleManager>
回答2:
Try using HttpContext to get current login user:
if (HttpContext.Current.User.IsInRole("Stream"))
{
}
来源:https://stackoverflow.com/questions/16112536/roles-issue-with-user-isinrole