0

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.

Bassie
  • 9,529
  • 8
  • 68
  • 159
  • You might find a hint to answer your query with this post: https://stackoverflow.com/questions/1382791/what-should-i-do-if-the-current-asp-net-session-is-null – Kevin Avignon Feb 28 '18 at 00:30
  • Using session implies a stateful web server. This does not scale. Generally, state is something I'd keep in a database. – spender Feb 28 '18 at 00:35
  • @spender I am retrieving the data from a SharePoint list, but CSOM is really slow, so I want to cache that data in the session – Bassie Feb 28 '18 at 00:54
  • 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. Aside from that, are certain that spClient.GetAllUsers() isn't returning null? – Obie Feb 28 '18 at 02:58
  • @Obie Thank you Obie - static property is exactly what I need as you are right - the list of users will always be the same (its all the users!) post an answer if you like and I'll accept – Bassie Feb 28 '18 at 03:10
  • Thanks @Bassie, I've been in a points drought for a while! – Obie Feb 28 '18 at 03:33

1 Answers1

1

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.

Obie
  • 447
  • 2
  • 5