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; }
圖示: