简体   繁体   English

ASP.NET Core:自定义cookie处理

[英]ASP.NET Core: custom cookie processing

I need to have some cookie processing in my app (update session variable on signing-in/out). 我需要在我的应用程序中进行一些cookie处理(登录/注销时更新会话变量)。 First, I have some identity config: 首先,我有一些身份配置:

    public void ConfigureServices(IServiceCollection services)
    {
        //omitted
        services.AddIdentity<ApplicationUser, IdentityRole>(i =>
        {
            i.Lockout = new LockoutOptions()
            {
                DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1),
                MaxFailedAccessAttempts = 5
            };
            i.Password.RequireDigit = true;
            i.Password.RequireLowercase = true;
        })
        //omitted
    }

As the documentation suggests I added cookie middleware into the pipeline like this: 正如文档所示,我将cookie中间件添加到管道中,如下所示:

    public void Configure(IApplicationBuilder app)
    {
        //omitted
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            Events = new CookieAuthenticationEvents
            {
                OnSigningIn = app.ApplicationServices
                        .GetRequiredService<MyService>().DoSomething
            }

        });

        app.UseIdentity();
        //omitted
    }

That all doesn't work. 这一切都行不通。 DoSomething isn't called. DoSomething没有被调用。 If I write a lambda in ConfigureServices it works: 如果我在ConfigureServices编写lambda,它的工作原理是:

i.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents    
{
    OnSigningIn = async context => { await Task.FromResult(1); }
};

So the question (actually two). 所以问题(实际上是两个)。 How can I request a service in the ConfigureServices method OR how make the Events in the UseCookieAuthentication work? 如何在ConfigureServices方法中请求服务或如何使UseCookieAuthentication中的UseCookieAuthentication有效?

一旦事件需要回调(稍后将在设置了所有服务时调用)并且回调接受可以访问HttpContext BasePrincipalContext ,我可以声明一个静态方法,其中HttpContext.RequestServices.GetRequiredService<Type>()可以调用HttpContext.RequestServices.GetRequiredService<Type>()以便获得一个需要的服务实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM