在我们的MVC应用程序中,我们绕过RolesProvider,转而将我们的角色缓存在一个将被传递的cookie中。根据几个关于互联网的建议,我们正在利用Application_AuthenticateRequest
事件,如下:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var user = HttpContext.Current.User;
if (user == null || !user.Identity.IsAuthenticated)
{
return;
}
// read the roles from the cookie and set a custom generic principal
var fi = (FormsIdentity)HttpContext.Current.User.Identity;
var httpCookie = HttpContext.Current.Request.Cookies["Roles"]; // custom cookie set during authentication
if (httpCookie != null)
{
string rolesCookie = httpCookie.Value;
var pmUserRoles = rolesCookie.Split(',');
GenericPrincipal gp = new GenericPrincipal(fi, pmUserRoles);
HttpContext.Current.User = gp;
}
}
我已经逐步完成了这个方法,并在我们的一些角色中添加了几个条件,并且在设置当前用户之后,User.IsInRole("rolename")
就像魅力一样。
但是,当试图在视图中进行相同的调用时:
@if(Request.IsAuthenticated)
{
if (User.IsInRole("role1") || User.IsInRole("role2"))
{
<!-- show something -->
}
else if (User.IsInRole("role3"))
{
<!-- show something else -->
}
}
无法访问角色。当我在此时深入了解用户时,在我确认用户在AuthenticateRequest
事件结束时拥有它们之后,看起来角色根本不存在。
This question有类似的问题,我只是在那里评论,但我想我不能因为我的低代表 - 但看起来这不仅仅是我的问题。
我也看了this question,它有类似的方法,但这给了我相同的结果。
对正在发生的事情提出任何建议或意见?
答案 0 :(得分:3)
我终于使用Application_OnPostAuthenticateRequest
处理程序代替Application_AuthenticateRequest
找到了答案。
由this answer提供(令人惊讶的是,该线程中没有被接受的那个!)。感谢Tiago Matias!
答案 1 :(得分:1)
尝试使用HttpContext.Current.User.IsInRole
代替User.IsInRole
。