且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有身份的ASP.NET Core 2.0中的Cookie到期

更新时间:2023-02-16 11:37:37

以下是我用来设置我使用的测试应用程序中cookie到期时间的方法.

The following is what I am using to set the expiry for the cookie in a test application that I use.

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();
        ...
    }
    ...
}

我认为这应该使您朝正确的方向前进.

I think this should get you going in the right direction.

这对我有用,而且我还没有发现任何问题.不过,距离Core 2.0 RTM仅几周了. :)

This works for me, and I haven't noticed any issues yet. Although, it's only been a couple of weeks since the Core 2.0 RTM. :)

希望这会有所帮助.