入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

asp.net core 2.0 Cookie 使用

创建时间:2017-08-19 投稿人: 浏览次数:2409

直接上代码

1、配置

startup.cs 中

public void ConfigureServices(IServiceCollection services)
{
    // 添加 Cook 服务
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/LogIn";
        options.LogoutPath = "/Account/LogOff";
    });

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ......
    // 使用Cook的中间件
    app.UseAuthentication();
    ......
}
2、登录
public IActionResult Login(){
    var user = new ClaimsPrincipal(
    new ClaimsIdentity(new[]
    { 
        new Claim(ClaimTypes.Name, username),
    },
    CookieAuthenticationDefaults.AuthenticationScheme));
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user, new Microsoft.AspNetCore.Authentication.AuthenticationProperties
    {
        IsPersistent = true,
        ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromDays(7)) // 有效时间
    });
    return view();
}
3、退出登录
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    return RedirectToAction("Login", "Account");
}
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。