Buscar contenidos

viernes, 6 de marzo de 2020

How To Use Session In .NET Core

https://thecodehubs.com/how-to-use-session-in-net-core/


Introduction

In this article, we will learn how to use sessions in our .NET Core Web applications. I assume that your web application is already created.

Prerequisite

  • .NET Core SDK
  • Visual Studio
To use the session first we need to install Nuget namely  “Microsoft.AspNetCore.Session”.
Go to Tools > NuGet Package Manager > Manage NuGet Packages For Solutions.
Click on Browse Tab and search for “Microsoft.AspNetCore.Session”. Click on search NuGet and click to Install button.
Now, We can use the session by following the below codes.
First we need to add a session in the ConfigureServices method of StartUp class.
  1. services.AddSession();
Now add a session in Configure method to configure the HTTP request pipeline.
  1. app.UseSession();
Startup class look like this
  1. public class Startup
  2. {
  3. public Startup(IConfiguration configuration)
  4. {
  5. Configuration = configuration;
  6. }
  7. public IConfiguration Configuration { get; }
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. public void ConfigureServices(IServiceCollection services)
  10. {
  11. services.Configure<CookiePolicyOptions>(options =>
  12. {
  13. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  14. options.CheckConsentNeeded = context => false;
  15. options.MinimumSameSitePolicy = SameSiteMode.None;
  16. });
  17. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  18. services.AddSession();
  19. services.AddHttpContextAccessor();
  20. }
  21. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  22. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  23. {
  24. if (env.IsDevelopment())
  25. {
  26. app.UseDeveloperExceptionPage();
  27. }
  28. else
  29. {
  30. app.UseExceptionHandler("/Home/Error");
  31. app.UseHsts();
  32. }
  33. app.UseHttpsRedirection();
  34. app.UseStaticFiles();
  35. app.UseCookiePolicy();
  36. app.UseSession();
  37. app.UseMvc(routes =>
  38. {
  39. routes.MapRoute(
  40. name: "default",
  41. template: "{controller=Home}/{action=Index}/{id?}");
  42. });
  43. }
  44. }

To Set Session
  1. public IActionResult Index()
  2. {
  3. HttpContext.Session.SetString(SessionName, "Faisal Pathan");
  4. HttpContext.Session.SetInt32(SessionAge, 24);
  5. return View();
  6. }
To Get Session
  1. public IActionResult About()
  2. {
  3. Var userName = HttpContext.Session.GetString("UserName");
  4. var code = HttpContext.Session.GetInt32("Code");
  5. return View();
  6. }
We can also set the whole class/object in the session
To Set/Get Object as JSON from Session
  1. public IActionResult Index()
  2. {
  3. // some object
  4. object value = new object();
  5. // set object value in session
  6. HttpContext.Session.SetString("Key Name", JsonConvert.SerializeObject(value));
  7. // get object value in session
  8. var sesionValue = HttpContext.Session.GetString("Key Name);
  9. var sessionObj = value == null ? default(T) : JsonConvert.DeserializeObject<T>(sesionValue);
  10. return View();
  11. }
We also can create an Extention method to use sessions globally in our application.
  1. public static class SessionExtensions
  2. {
  3. public static void SetObjectAsJson(this ISession session, string key, object value)
  4. {
  5. session.SetString(key, JsonConvert.SerializeObject(value));
  6. }
  7. public static T GetObjectFromJson<T>(this ISession session, string key)
  8. {
  9. var value = session.GetString(key);
  10. return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
  11. }