使用AddUserToRole时找不到用户

时间:2015-04-15 06:03:22

标签: asp.net membership-provider asp.net-4.5 role-manager

我试图将用户分配给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>

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法,看看这是否有帮助。至少你会知道提供商究竟发生了什么:

    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...
    }