[C#] 設定 與 取得 Cookie
在寫Web的時候,如果有遇到存參數的情境,若非權限相關的資訊,儘量能存在client端,就存在client端,畢竟Server的空間也有限,所以能省則省。那麼這時候對Cookie做設定與取得就會變成常態,因此建議可以寫個Extension來做處理。
範例:
1.建立一個Controller-Extension
/// <summary>
/// Controller-Extension
/// </summary>
public static class ControllerExtension
{
/// <summary>
/// 設定 Cookice
/// </summary>
/// <param name="controller"></param>
/// <param name="cookieName"></param>
/// <param name="data">object</param>
/// <param name="timeOutMin">time out 時間(單位:分)</param>
public static void SetCookice(this Controller controller, string cookieName, object data, int? timeOutMin = null)
{
var js = new JavaScriptSerializer();
var cookie = new HttpCookie(cookieName)
{
Value = js.Serialize(data),
// 設定預設路徑 避免Cookie自行設定路徑
Path = "/"
};
if (timeOutMin != null)
{
// 設定過期時間
cookie.Expires = DateTime.Now.AddMinutes((int)timeOutMin);
}
// 寫到用戶端
controller.Response.Cookies.Add(cookie);
}
/// <summary>
/// 取得 Cookice
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="controller"></param>
/// <param name="cookieName"></param>
/// <returns></returns>
public static T GetCookice<T>(this Controller controller, string cookieName)
{
var js = new JavaScriptSerializer();
var result = controller.Request.Cookies[cookieName];
if (result is null)
{
return default(T);
}
return js.Deserialize<T>(result.Value);
}
}
2.在Controller的使用方法
public ActionResult Index()
{
//測試儲存資料
string test = "TestValue";
//設定Cookie
this.SetCookice("Test", test);
//取得Cookie
var value = this.GetCookice<string>("Test");
return View();
}
留言
張貼留言