当在asp.net mvc 4.5中向角色添加用户时,i';m得到一个错误-“;用户(用户名)未找到”;

本文关键字:用户 一个 错误 mvc asp net 角色 添加 当在 | 更新日期: 2023-09-27 17:59:17

这是我的帐户登录控制器。(我的"auth"类方法返回"user"或"admin",并相应地登录)。

[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(用户名,"admin")的用户时,我收到一个错误,它找不到用户(用户名)。我不知道为什么!

以下是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>

当在asp.net mvc 4.5中向角色添加用户时,i';m得到一个错误-“;用户(用户名)未找到”;

问题是您没有在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" />