2015-04-15 66 views
0

我正嘗試將用戶分配給asp.net成員資格中的角色。使用AddUserToRole時未找到用戶

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

但我不斷收到下面的錯誤。

未找到用戶'Upendra'。

但是,'Upendra'用戶確實存在於Users表中,並且也存在於Roles表中的'Admin'角色。

我的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> 
+0

問題發生在任何想要添加到該角色的外部用戶上? – zed

+0

您是否嘗試過我在下面的答案中提供的解決方案?你的問題解決了嗎? – SBirthare

+0

是這個問題解決..如果所以請發表答案 – Sachu

回答

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... 
    } 
相關問題