Advertisement
otkalce

State persistence - session

Mar 21st, 2023
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.71 KB | Source Code | 0 0
  1. // *** To use session, you need to configure session sevices ***
  2. builder.Services.AddDistributedMemoryCache();
  3. builder.Services.AddSession();
  4.  
  5. // *** Also, you need to add session middleware - right before mapping of the controllers ***
  6. app.UseSession();
  7.  
  8. // *** Action that uses session to store some data ***
  9. [HttpGet("[action]")]
  10. public ActionResult<Receipt> SessionData(string? data)
  11. {
  12.     if (!string.IsNullOrEmpty(data))
  13.     {
  14.         HttpContext.Session.SetString("sessionData", data);
  15.  
  16.         return Ok($"Session data set to {data}.");
  17.     }
  18.     else
  19.     {
  20.         var storedData = HttpContext.Session.GetString("sessionData");
  21.  
  22.         return Ok($"Current session data is {storedData}.");
  23.     }
  24. }
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement