我在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请求图像也会调用这种方法!
解决方法
我找到了一个问题的答案.
在loggin_in事件中,我应该保存身份验证cookie(我可以在UserData属性中存储我在customPrincipal中需要的所有信息),在Application_PostAuthenticateRequest中我应该从该cookie创建CustomPrincipal.
这样这个事件会触发每个请求,但是我没有命中数据库 – 我从cookie中读取数据.
我跟着http://www.ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
在我的情况下代码是:
void Application_PostAuthenticateRequest(object sender,EventArgs args) { HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie == null) return; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); string[] customData = authTicket.UserData.Split(new Char[] { '|' }); if (Context.User.Identity.IsAuthenticated == true) { if (Context.User.Identity.AuthenticationType == "Forms") { Context.User = new CustomPrincipal(customData,Context.User); Thread.CurrentPrincipal = Context.User; } } }