【发布时间】:2023-03-14 14:18:02
【问题描述】:
我在成员资格和角色管理方面有非常基本的需求。我在成员资格方面取得了成功,并且能够使用 [Authorize] 过滤器,但是 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")] 过滤器失败。
【问题讨论】:
-
您是否在 global.asax 中重新处理了 Identity 对象?
-
你能稍微扩展一下吗?我不清楚你的意思。
-
这就是答案,但我无法将评论标记为答案。
标签: asp.net asp.net-mvc