简体   繁体   English

将用户添加到asp.net mvc 4.5中的角色时,出现错误-“未找到用户(用户名)”

[英]When adding a user to a role in asp.net mvc 4.5, i'm getting an error- “user (user name) not found”

Here is my account login controller. 这是我的帐户登录控制器。 (My "auth" class method returns "user" or "admin" and is logged in accordingly). (我的“ 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");
    }

Edited 编辑

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

The problem is when I add a user with Roles.AddUserToRole(userName, "admin"), I get an error that it cannot find user(userName). 问题是,当我添加一个具有Roles.AddUserToRole(userName,“ admin”)的用户时,出现错误,提示它找不到用户(userName)。 I'm at a loss as to why! 我茫然为什么!

Here's the role manager details from web.config: 以下是来自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>

The problem is you are not setting roleManager properly in webconfig. 问题是您没有在webconfig中正确设置roleManager。 change your webconfig as below. 如下更改您的webconfig。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM