From c5f0478e082ebbeda6874916af0f54a87f2c0904 Mon Sep 17 00:00:00 2001 From: luke-else <52086083+luke-else@users.noreply.github.com> Date: Sun, 7 Nov 2021 22:06:16 +0000 Subject: [PATCH] Add Session Extensions --- Sessions/SessionExtensions.cs | 19 +++++++++++++++++++ Startup.cs | 3 +++ 2 files changed, 22 insertions(+) create mode 100644 Sessions/SessionExtensions.cs diff --git a/Sessions/SessionExtensions.cs b/Sessions/SessionExtensions.cs new file mode 100644 index 0000000..5b1577a --- /dev/null +++ b/Sessions/SessionExtensions.cs @@ -0,0 +1,19 @@ +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; + +namespace EFB.Sessions +{ + public static class SessionExtensions + { + public static void SetObject(this ISession session, string key, object value) + {//Sets the object of a session to Object + session.SetString(key, JsonConvert.SerializeObject(value)); + } + + public static T GetObject(this ISession session, string key) + {//Gets a session of known type (T) + var value = session.GetString(key); + return value == null ? default(T) : JsonConvert.DeserializeObject(value); + } + } +} \ No newline at end of file diff --git a/Startup.cs b/Startup.cs index 1902a2e..90010f4 100644 --- a/Startup.cs +++ b/Startup.cs @@ -24,6 +24,7 @@ namespace EFB public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); + services.AddSession(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -44,6 +45,8 @@ namespace EFB app.UseRouting(); + app.UseSession(); + app.UseAuthorization(); app.UseEndpoints(endpoints =>