Bassie
Bassie

Reputation: 10380

Session variable is cleared before calling controller

I need to keep a Session variable updated at all times while a user is using the application.

I have tried the following approaches:

public class MyController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var a = filterContext.HttpContext.Session["SPUsers"];
        if (filterContext.HttpContext.Session["SPUsers"] != null)
        {
            new Task(InitialiseUsers).Start();
        }
        base.OnActionExecuting(filterContext);
    }

    protected override void Initialize(RequestContext requestContext)
    {
        var a = requestContext.HttpContext.Session["SPUsers"];
        if (requestContext.HttpContext.Session["SPUsers"] == null)
        {
            new Task(InitialiseUsers).Start();
        }
        base.Initialize(requestContext);
    }

    private void InitialiseUsers()
    {
        var spClient = new SPClient(ConfigurationManager.AppSettings["ADVBaseUrl"]);
        Session["SPUsers"] = spClient.GetAllUsers();
    }
}

Where all my other controllers inherit from MyController.

I can see that the OnActionExecuting and Initialize methods are called when I navigate to a page, and also that the InitialiseUsers method is called when the SPUsers session variable is null.

The problem is, is that that session variable is always null.

Why is that?

Why does the value not get updated in InitailiseUsers? Or is it that the value is cleared beofre reaching the other 2 methods?

Appreciate any guidance.

Upvotes: 0

Views: 230

Answers (1)

Obie
Obie

Reputation: 477

It looks like everybody would end up with the same list of users ine session variable. Maybe a singleton (application context or a static property) would work better for scalability.

Upvotes: 1

Related Questions