英文:
How to get cookie renewal information in .NET Core 3.1 with CookieAuthentication?
问题
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context =>
{
if (context.ShouldRenew)
{
Console.WriteLine("Cookie expire time should be updated");
// Write your desired logic here
}
return Task.CompletedTask;
}
};
英文:
I am using .NET Core 3.1 and would like to know how to get cookie renewal information when a user's login cookie expire time is extended.
I have tried adding the following code to startup.cs
, but context.ShouldRenew
always returns false
, even though the login cookie's expire time has been extended:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Member/Login");
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromSeconds(10);
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context =>
{
if (context.ShouldRenew)
{
Console.WriteLine("Cookie expire time should be update");
// I want to write some text
// But `context.ShouldRenew` always get false
}
return Task.CompletedTask;
}
};
});
What should be the correct way to get cookie renewal information in .NET Core 3.1 with CookieAuthentication?
答案1
得分: 1
我认为你需要使用另一个属性来检测 cookie 是否过期。该属性的描述 ShouldRenew
:
> 如果为 true,cookie 将被续订
换句话说:即使 cookie 已过期,它也可以为 false。
你可以使用 HttpContext
属性来检查是否有任何 cookie 过期:
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context =>
{
var cookie = context.HttpContext.Request.Cookies["YOUR_COOKIE_NAME"];
if (cookie.Expires < DateTime.Now)
{
// 在这里编写你的代码...
}
return Task.CompletedTask;
}
};
英文:
I think you need to use another property to detect if cookie has expired. Description of the property ShouldRenew
:
> If true, the cookie will be renewed
In other words: It can be false, even if cookies have expired.
You can use HttpContext
property to check if any cookies have expired:
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = context =>
{
var cookie = context.HttpContext.Request.Cookies["YOUR_COOKIE_NAME"];
if (cookie.Expires < DateTime.Now)
{
// Your code here...
}
return Task.CompletedTask;
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论