需要帮助实现简单的角色管理

时间:2010-11-27 17:25:39

标签: asp.net asp.net-mvc

我对会员和角色管理有非常基本的需求。我在成员资格方面取得了成功,并且能够使用[授权]过滤器,但是IsInRole()以及随之而来的一切都失败了。我希望有人可以指出我哪里出错了。

1)在控制器上调用登录操作:

[HttpPost]
    public ActionResult LogOn(LoginVM model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (_employeeService.Login(model))
            {
                _employeeService.CreateTicket(model);

                FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);

                if (!String.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

2)CreateTicket(LovinVM模型)如下所示:

public HttpCookie CreateTicket(LoginVM input)
    {
        string rolesList;
        using (var tx = _session.BeginTransaction())
        {
            Employee employee = _employeeRepository.GetByUsername(input.Username);

            if (employee.Roles.Count >= 0)
            {
                string[] roles = new string[employee.Roles.Count];
                for (int i = 0; i < employee.Roles.Count; i++)
                {
                    roles[i] = employee.Roles.ElementAt(i).Name;
                }

                rolesList = string.Join(",", roles);
            }
            else
            {
                rolesList = string.Empty;
            }

            tx.Commit();
        }

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, input.Username, DateTime.Now, DateTime.Now.AddMinutes(20), false, rolesList);

        return new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
    }

如果在创建故障单后检查用户是否处于角色中,但在设置身份验证cookie之前,我会得到一个真值:

_employeeService.CreateTicket(model);

bool test = User.IsInRole("Role1");

FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);

如果我向site.master添加一个检查以显示/隐藏基于角色的菜单项,则不再为该用户列出任何角色。我已经尝试了Page.User.IsInRole(“Role1”)和HttpContext.Current.User.IsInRole(“Role1”)这两者都不是真的。我在[Authorize(Roles =“Role1”)]过滤器上也收到了失败。

2 个答案:

答案 0 :(得分:0)

我不确定您是否将您的会员资格从旧的基本会员资格提供者中删除,但是查看我的早期MVC项目之一...当用户成功验证时会调用一个方法... < / p>

if (MembershipService.ValidateUser(model.UserName, model.Password))
            {
                FormsService.SignIn(model.UserName, model.RememberMe);

虽然我不是会员服务方面的专家,但如果您知道我的意思,一旦他们“登录”,就会听起来好像您的用户没有正确登录。

表示FormsService.SignIn()的行......你的LogOn方法中没有任何类似内容。

答案 1 :(得分:0)

单独注意 - 我很好奇为什么你在事务上调用commit似乎没有进行任何事务性工作?您获得一个用户,并创建一个票证(转到cookie。

相关问题