6

Using asp.net core how to create a session variable to store the list kind of objects and how to retrieve the values from the view

was trying

HttpContext.Session.SetString("Test", listObject);

.

2 Answers 2

11

First, you need to add more config at Startup class.

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDistributedMemoryCache();                      

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.Cookie.IsEssential = true;
        });           

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseStatusCodePages();
    app.UseStaticFiles();
    app.UseSession();
    app.UseMvc(routes =>
    {
        // Default Route
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

//Add the following extension methods to set and get serializable objects:

public static class SessionExtensions
    {
        public static T GetComplexData<T>(this ISession session, string key)
        {
            var data = session.GetString(key);
            if (data == null)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(data);
        }

        public static void SetComplexData(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }
    }

public IActionResult Index()
        {
            List<BookingModel> data = new List<BookingModel>();

            for (int i = 1; i < 10; i++)
            {                
                BookingModel obj = new BookingModel
                {
                    BookingId = i,
                    BookingRefNo = $"00{i}",
                    FullName = $"A{i}",
                    MobileNo = $"(00)-{i}",
                    Email = $"abc{i}@gmail.com"
                };
                data.Add(obj);
            }

            HttpContext.Session.SetComplexData("loggerUser", data);
            return View();
        }

public IActionResult Privacy()
        {
            List<BookingModel> data = HttpContext.Session.GetComplexData<List<BookingModel>>("loggerUser");
            return View();
        }

And you can visit this link to refer more: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#session-state

Hope to help, my friend :))

3
  • yes i have tried above process but problem is session object is allowing us to store single object ..like we can set a single string value and get a single string value...there is no overloaded method in session object that accepting list.
    – Cust_1
    Commented Jul 1, 2019 at 10:14
  • @Gandhi: I updated my answer. Please check it, my friend :))
    – Tomato32
    Commented Jul 1, 2019 at 11:32
  • Working fine as want.
    – anand
    Commented Feb 11, 2022 at 10:53
0

Try IHttpContextAccessor insted of HttpContext to get the current section keys.

The code:

public class UserRepository : IUserRepository
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserRepository(IHttpContextAccessor httpContextAccessor) =>
        _httpContextAccessor = httpContextAccessor;

    public void LogCurrentUser()
    {
        var username = _httpContextAccessor.HttpContext.User.Identity.Name;

        // ...
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.