Advertisement
otkalce

State storage - cookie

Mar 20th, 2023
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.00 KB | Source Code | 0 0
  1. [HttpGet("[action]")]
  2. public ActionResult<Receipt> CookieData(string? data)
  3. {
  4.     // Append (or recreate) cookie
  5.     HttpContext.Response.Cookies.Append(
  6.         "timestamp",
  7.         DateTime.Now.ToUniversalTime().ToString(),
  8.         new CookieOptions
  9.         {
  10.             Expires = DateTimeOffset.Now.AddDays(1), // Make it a permanent cookie
  11.             Domain = Request.Host.Host,
  12.             Path = "/",
  13.         });
  14.  
  15.     // If a value is passed to action and bound, append (or recreate) cookie
  16.     // Otherwise read cookie from request
  17.     if (!string.IsNullOrEmpty(data))
  18.     {
  19.         HttpContext.Response.Cookies.Append(
  20.             "data",
  21.             data,
  22.             new CookieOptions
  23.             {
  24.                 Expires = null, // Make it a session cookie
  25.             });
  26.  
  27.  
  28.         return Ok($"Data cookie set to {data}.");
  29.     }
  30.     else
  31.     {
  32.         var storedData = HttpContext.Request.Cookies["data"];
  33.  
  34.         return Ok($"Current data cookie is {storedData}.");
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement