0

I am using MVC application. I am updating an object's properties with the user related information in the HomePage controller's Display action method. HomePage/Display is the first action method that gets executed when the application url is opened. Display action fetches the user related information like past orders, ongoing orders etc from the database and the same is populated in the userInformation object.

I save this userInformation object in a session.

var userData = HttpContext.Current.Session["UInfo"] as userInformation;

I need this userData object in all the controllers. Hence in other controllers I access the userData object using the session i.e HttpContext.Current.Session["UInfo"] as userInformation. But if the thread is different then HttpContext.Current.Session["UInfo"] becomes null.

I have googled for the solution but most of them refer to storing simple string or using ViewModel for _Layout. I am aware that we can do it using TempData..but I am looking for any better or alternate solution for this.

How do i reuse a object that gets initialized in one controller and reuse the object in all the other controllers and views

Thank you.

Hgrbz
  • 185
  • 3
  • 12
raki.dbit
  • 152
  • 1
  • 11

1 Answers1

0

Session and Cache are in fact the better options to keep users profile in memory and after user logout or expiring session memory will be freed.

You could set a property in each controller (or a base controller ideally) and use that property across all threads.

public class YourController : Controller
{   
    HttpContext context = HttpContext.Current;

    public ActionResult YourAction()
    {
        context.WhateverYouWant
    }
}
iamdlm
  • 1,885
  • 1
  • 11
  • 21
  • Does the HttpContext.Current persist the data in a multi thread application. I am currently using session but the values become null when a different thread gets associated with the request. – raki.dbit Aug 31 '21 at 11:09
  • No, it does not. But you can use a property to store the context when your controllers are initialized. See [this answer](https://stackoverflow.com/a/19319205/3990896). – iamdlm Aug 31 '21 at 11:12