加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 在哪里创建自定义IPrincipal对象?

发布时间:2020-12-16 06:29:15 所属栏目:asp.Net 来源:网络整理
导读:我在global.asax中使用Application_PostAuthenticateRequest事件来创建自定义IPrincipal对象 void Application_PostAuthenticateRequest(object sender,EventArgs args){ if (Context.User.Identity.IsAuthenticated == true) if (Context.User.Identity.Aut
我在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;
            }
        }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读