【发布时间】:2013-05-17 13:55:27
【问题描述】:
全局 asax 中的 HttpContext.Current.User 是否与操作方法中的 HttpContext.User 不同?我为用户分配了一些角色,但他们似乎迷路了。
下面的代码显示了正在发生的事情。当用户登录时,这两个断言都会被命中,首先是全局 asax,然后是 action 方法。但是它们给出了不同的结果。
首先是这个:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// ... omitted some code to check user is authenticated
FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
string[] roles = new string[] { "admin", "user" };
HttpContext.Current.User =
new System.Security.Principal.GenericPrincipal(identity, roles);
Assert(HttpContext.User.IsInRole("admin"));
}
然后在我的操作方法中:
public ActionResult Index()
{
bool isAdmin = HttpContext.User.IsInRole("admin");
Assert(isAdmin); // this fails, isAdmin is false
// ...
}
我使用了以下资源
http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html
【问题讨论】:
-
我已经扩展了我的答案,包括关于为什么会发生这种情况的评论,以及一个插图,希望对您有所帮助。如果您真的必须使用它而不是
WebSecurity,请尝试Application_OnPostAuthenticateRequest
标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 forms-authentication