services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(opt => { opt.LoginPath = new PathString("/Home/Index/"); });
HttpContext.Response.Cookies.Append("getCookie", "setCookieValue");
var getCookie = ""; HttpContext.Request.Cookies.TryGetValue("getCookie", out getCookie);
app.UseCookiePolicy();
public class CookieHelper:Controller { /// <summary> /// 添加cookie緩存不設置過時時間 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void AddCookie(string key, string value) { try { HttpContext.Response.Cookies.Append(key, value); } catch (Exception ex) { throw; } } /// <summary> /// 添加cookie緩存設置過時時間 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="time"></param> public void AddCookie(string key,string value,int time) { HttpContext.Response.Cookies.Append(key, value,new CookieOptions { Expires=DateTime.Now.AddMilliseconds(time) }); } /// <summary> /// 刪除cookie緩存 /// </summary> /// <param name="key"></param> public void DeleteCookie(string key) { HttpContext.Response.Cookies.Delete(key); } /// <summary> /// 根據鍵獲取對應的cookie /// </summary> /// <param name="key"></param> /// <returns></returns> public string GetValue(string key) { var value = ""; HttpContext.Request.Cookies.TryGetValue(key,out value); if (string.IsNullOrWhiteSpace(value)) { value = string.Empty; } return value; } }
public class HomeController : CookieHelper { public IActionResult Index() { AddCookie("getCookie", "這是一個測試存cookie"); return View(); } } public class cookieController : CookieHelper { public IActionResult Index() { ViewBag.cookie = GetValue("getCookie"); return View(); } }
歡迎你們掃描下方二維碼,和我一塊兒學習更多的知識😊api