我在global.asax中使用Application_PostAuthenticateRequest事件来创建自定义IPrincipal对象
void Application_PostAuthenticateRequest(object sender, EventArgs args)
{
if (Context.User.Identity.IsAuthenticated == true)
if (Context.User.Identity.AuthenticationType == "Forms")
{
Context.User = new CustomPrincipal(Context.User);
Thread.CurrentPrincipal = Context.User;
}
}
在我想要的应用程序中使用获取有关已登录用户的更多信息 . 我认为在用户进行身份验证时会调用一次,但我注意到在同一个登录用户的每个页面请求上都会调用它几次 . 我发现即使从AppThemes请求图像也会调用这种方法!
我应该在哪里创建该对象,以避免为每个用户多次调用此方法?
2 回答
我找到了问题的答案 .
在loggin_in事件中,我应该保存身份验证cookie(我可以在UserData属性中存储我在customPrincipal中需要的所有信息),在Application_PostAuthenticateRequest中,我应该从该cookie创建CustomPrincipal . 这样这个事件会触发每个请求但我没有命中数据库 - 我从cookie中读取数据 .
我跟着http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
在我的情况下代码是:
Context.User不会跨请求保存新主体;您必须在每个请求上创建自定义主体 . 因此,最好将此代码保留在此处 . 否则,它将恢复为FormsPrincipal或WindowsPrincipal,具体取决于应用程序身份验证模式 .
HTH,
布赖恩