C# ASP.NET核心:自定义cookie处理
我需要在我的应用程序中进行一些cookie处理(登录/注销时更新会话变量)。首先,我有一些身份配置:C# ASP.NET核心:自定义cookie处理,c#,cookies,asp.net-core,C#,Cookies,Asp.net Core,我需要在我的应用程序中进行一些cookie处理(登录/注销时更新会话变量)。首先,我有一些身份配置: public void ConfigureServices(IServiceCollection services) { //omitted services.AddIdentity<ApplicationUser, IdentityRole>(i => { i.Lockout = new
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
}
所以这个问题(实际上是两个问题)。如何在
ConfigureServices
方法中请求服务,或者如何使UseCookieAuthentication
中的事件工作?一旦事件需要回调(将在设置所有服务后调用)回调接受BasePrincipalContext
,通过它可以访问HttpContext
,我可以声明一个静态方法,在这个方法中可以调用HttpContext.RequestServices.GetRequiredService()
,以便在事件需要回调时,我立即获得一个Required服务实例(当所有服务都设置好后,将调用它),回调接受BasePrincipalContext
,通过它可以访问HttpContext
,我可以声明一个静态方法,在该方法中可以调用HttpContext.RequestServices.GetRequiredService()
,从而获得一个需要的服务实例
public void Configure(IApplicationBuilder app)
{
//omitted
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
Events = new CookieAuthenticationEvents
{
OnSigningIn = app.ApplicationServices
.GetRequiredService<MyService>().DoSomething
}
});
app.UseIdentity();
//omitted
}
i.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnSigningIn = async context => { await Task.FromResult(1); }
};