1, 首先我们在 Startup 下面的 ConfigureServices 中注册授权认证服务以及 AddCookie
- services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
- .AddCookie(opt => {
- opt.LoginPath = new PathString("/Home/Index/");
- });
2, 然后可以在需要使用 cookie 的地方添加
HttpContext.Response.Cookies.Append("getCookie", "setCookieValue");
3, 然后我们需要使用的时候直接取出 cookie 的值
- var getCookie = "";
- HttpContext.Request.Cookies.TryGetValue("getCookie", out getCookie);
4, 到这里都是可以成功的, 然后我们清除浏览器缓存之后再来尝试这样来处理 cookie. 发现 Append 和 TryGetValue 都是没有值的. 原因是 AspNetCore2.1 支持了 2018 年 5 月 25 号出台的 GDPR 规范, 该规范认为 cookie 是用户的隐私数据, 如果要使用的话, 必须征得用户同意. 我们可以把 Configure 中的
App.UseCookiePolicy();
这一行代码注释掉. 然后我们再次试试, 发现存取 cookie 都是正常的了.
来源: http://www.jianshu.com/p/9e453fd90112