带有标识的 ASP.NET Core 2.0 中的 Cookie 到期

gro*_*kky 5 .net asp.net asp.net-identity asp.net-core asp.net-core-2.0

环境:ASP.NET Core 2.0,带有 cookie 的标识。

Startup.ConfigureServices()那里是这样的:

services.ConfigureApplicationCookie(options => {
  options.ExpireTimeSpan = TimeSpan.FromDays(14);
  options.Cookie.Expiration = TimeSpan.FromDays(14);
});
Run Code Online (Sandbox Code Playgroud)

第一个来自CookieAuthenticationOptions. 第二个来自CookieBuilder. 文档还提到Microsoft.AspNetCore.Http.CookieOptions.Expires(尽管它在该 lambda 中不可用)。

这些有什么区别?在 Core2 中设置到期时间的正确方法是什么?

R. *_*rds 4

以下是我在我使用的测试应用程序中用来设置 cookie 过期时间的内容。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to add services to the container
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        ...

        ...  // before services.AddMvc();!
        services.AddAuthentication().AddCookie(options => {
            options.Cookie.Expiration = TimeSpan.FromDays(14);
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
            options.Cookie.Name = "MyCookieName";
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/Forbidden";
        });

        // OR Perhaps, this could be what you need
        services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.Expiration = TimeSpan.FromDays(150);
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
            options.Cookie.Name = "MyCookieName";
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/Forbidden";
        });
        ...
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        ... // before app.UseMvc();!
        app.UseAuthentication();
        // WAS -> app.UseCookieAuthentication();
        ...
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我认为这应该让你朝着正确的方向前进。

这对我有用,我还没有注意到任何问题。不过,距 Core 2.0 RTM 发布仅几周时间。:)

希望这可以帮助。