1.需要在startup.cs中添加cookie的服务
services.Configure<CookiePolicyOptions>(option =>{ ???????????????option.CheckConsentNeeded=ContextBoundObject=>true; ???????????????option.MinimumSameSitePolicy=SameSiteMode.None; ???????????}); //添加cookie的服务
图示:
2.在startup.cs中启动服务
app.UseCookiePolicy(); ?????//启用cookie服务
图示:
startup.cs中添加的引用:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Http;using Microsoft.Extensions.DependencyInjection;//参数验证,路由的参数验证配置using Microsoft.AspNetCore.Routing;using Microsoft.AspNetCore.Routing.Constraints;//mysql基础配置引用using Online.Examination.Web.Repositories;using Online.Examination.Web.Controllers;using Online.Examination.Web.Repositories.DBBase;
图示:
3.在控制层使用Append方法向客户端添加cookie
//cookie的引用 需要引用这三个包
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.CookiePolicy;
using Microsoft.AspNetCore.Http.Features;
图示:
4.最后一步:很重要 如果服务器要想客户端存储cookie,客户端需要向服务器发送第一次请求,请求允许使用cookie
所以需要在控制层中写入方法,这个方法只需要请求一次,就可以向客户端存储cookie了
5.js代码示例
$(function() { ???$.post("/login/OkCookie", function() {}) //如果使用cookie,客户端必须向服务端发送一次请求////})function login() { ???$(".error").text(""); ???var uname = $("input[name=‘name‘]").val(); ???var pwd = $("input[name=‘pwd‘]").val(); ???var type = $("input[name=‘login_type‘]:checked").val(); ???if (uname == "" || pwd == "") return false; ???$.post("/login/login", { "uname": uname, "pwd": pwd, "type": type }, function(msg) { ???????if (msg.message == "success") { ???????????window.location.href = "index.html?id=" + msg.users.name; ???????} else { ???????????$(".error").text("密码或账号错误"); ???????} ???})}
图示:
6.关于cookie其他的使用方法
代码:
protected void DeleteCookies(string key) ???//删除指定的cookie ???????{ ???????????HttpContext.Response.Cookies.Delete(key); ???????} ???????protected string GetCookies(string key) ????//获取指定的cookie ???????{ ???????????HttpContext.Request.Cookies.TryGetValue(key, out string value); ???????????if (string.IsNullOrEmpty(value)) ???????????????value = string.Empty; ???????????return value; ???????}
图示:
ASP.NET Core2.2 和2.1 版本中对cookie的设置和存储
原文地址:https://www.cnblogs.com/han-guang-xue/p/10612265.html