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

我在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;
            }
        }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....