2015-06-23 35 views
1

這是我的帳戶登錄控制器。 (我的「auth」類方法返回「user」或「admin」並相應地登錄)。將用戶添加到asp.net mvc 4.5中的角色時,出現錯誤 - 「未找到用戶(用戶名)」

[HttpPost] 
    public ActionResult Login(string userName, string pass) 
    { 
     Auth auth = new Auth(); 
     if (auth.MyAuth(userName) == "user") 
     { 
      FormsAuthentication.SetAuthCookie(userName, true); 
      return RedirectToAction("Index", "Home"); 
     } 

     else if(auth.MyAuth(userName) == "admin") 
     { 
      FormsAuthentication.SetAuthCookie(userName, true); 
      if (!Roles.RoleExists("admin")) 
      { 
       Roles.CreateRole("admin"); 
      } 
      if (!Roles.IsUserInRole(userName, "admin")) 
      { 
       Roles.AddUserToRole(userName, "admin"); 
      } 

      RedirectToAction("Index", "Home"); 
     } 
     return RedirectToAction("Login"); 
    } 

編輯

public class Auth 
{ 
    public string MyAuth(string userName) 
    { if (userName.Length == 4) 
    { return "user"; } 
    else if (userName.Length == 5) 
     { return "admin"; } 
    return "unauth"; } } 

問題是,當我增加一個用戶與Roles.AddUserToRole(用戶名, 「管理員」),我得到一個錯誤,它無法找到用戶(用戶名)。我不知道爲什麼!

這裏的角色管理的細節,從web.config中:

<roleManager enabled="true" defaultProvider="DefaultRoleProvider"> 
<providers> 
<add name="DefaultRoleProvider" 
    type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, 
    Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    connectionStringName="DefaultConnection" applicationName="/" /> 
</providers> 
</roleManager> 
+0

公共類驗證 { 公共字符串MyAuth(用戶名字符串) { 如果(userName.Length == 4){ 返回 「用戶」; } else if(userName.Length == 5) { return「admin」; } return「unauth」; } } – spooky123

+0

https://msdn.microsoft.com/en-us/library/system.web.security.roles.adduserstoroles(v=vs.110).aspx – spooky123

+0

我的不好,我發佈了錯誤的鏈接。這是addusertorole接受兩個字符串的正確鏈接。 https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB4QFjAA&url=https%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary% 2Fsystem.web.security.roles.addusertorole(v%3Dvs.110).aspx&ei = I8WIVZuFIIHm-AGjvKCQBw&usg = AFQjCNH5vOWVez0eodHWANVxmaruOhx7gQ&sig2 = _GVDpCeGxJwHj6mijlwhKQ – spooky123

回答

1

的問題是你是不是在webconfig正確設置roleManager。 如下改變你的webconfig。

<roleManager enabled="true" 
cacheRolesInCookie="true" 
cookieName=".ASPXROLES" 
cookieTimeout="30" 
cookiePath="/" 
cookieRequireSSL="false" 
cookieSlidingExpiration="true" 
cookieProtection="All" 
defaultProvider="AspNetSqlRoleProvider" 
createPersistentCookie="false" maxCachedResults="25" /> 
相關問題