0

我正在尝试将用户分配给 asp.net 成员资格中的角色。

protected void btnAssignUser_Click(object sender, EventArgs e)
        {
            Roles.AddUserToRole("Upendra", "Admin"); 
        }

但我不断收到以下错误。

未找到用户“Upendra”。

但是,“Upendra”用户确实存在于“用户”表中,并且“管理员”角色也存在于“角色”表中。

我的 web.config 设置如下

<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=IROSHEN-PC;Initial Catalog=IndunilaDB;Integrated Security=true;" />

  </connectionStrings>
      <profile defaultProvider="DefaultProfileProvider">
          <providers>
            <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
          </providers>
        </profile>
        <membership defaultProvider="DefaultMembershipProvider">
          <providers>
            <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
          </providers>
        </membership>
        <roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPXROLES"
    cookieTimeout="30" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true"
    cookieProtection="All" defaultProvider="DefaultRoleProvider" createPersistentCookie="false"
    maxCachedResults="25">
          <providers>
            <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="IndunillaWeb" />
          </providers>
        </roleManager>
4

1 回答 1

0

您可以尝试以下方法,看看是否有帮助。至少你会知道 Provider 到底发生了什么:

    public void AssignUserToRole(string username, string roleName)
    {
        if (Roles.RoleExists(roleName))
        {
            string[] rolesArray = Roles.GetRolesForUser(username);
            if (rolesArray.Length > 0)
            {
                // One user should be in one role so remove previous role
                Roles.RemoveUserFromRoles(username, rolesArray);
            }
            Roles.AddUserToRole(username, roleName);
        }
        else
            // RoleName does not exist, You may want to handle this case.
            // May just add the role and call this method again or throw...
    } 
于 2015-04-15T11:30:48.857 回答