Search code examples
asp.net-coresessioncachingrazorsession-variables

Is there a Session-unique identifier that can be used as a cache key name?


I'm porting a legacy ASP.NET WebForms app to Razor. It had stored an object in the Session collection. Session storage is now limited to byte[] or string. One technique is to serialize objects and store as a string, but there are caveats. Another article suggested using one of the alternative caching options, so I'm trying to use MemoryCache.

For this to work as a Session replacement, I need a key name that's unique to the user and their session.

I thought I'd use Session.Id for this, like so:

ObjectCache _cache = System.Runtime.Caching.MemoryCache.Default;

string _keyName = HttpContext.Session.Id + "$searchResults";

//(PROBLEM: Session.Id changes per refresh)


//hit a database for set of un-paged results
List<Foo> results = GetSearchResults(query);

if (results.Count > 0)
{
    //add to cache
    _cache.Set(_keyName, results, DateTimeOffset.Now.AddMinutes(20));

    BindResults();
}


//Called from multiple places, wish to use cached copy of results
private void BindResults()
{
    CacheItem cacheItem = _cache.GetCacheItem(_keyName);

    if (cacheItem != null) //in cache
    {
        List<Foo> results = (List<Foo>)cacheItem.Value;

        DrawResults(results);
    }
}

...but when testing, I see any browser refresh, or page link click, generates a new Session.Id. That's problematic.

Is there another built-in property somewhere I can use to identify the user's session and use for this key name purpose? One that will stay static through browser refreshes and clicks within the web app?

Thanks!


Solution

  • The answer Yiyi You linked to explains it -- the Session.Id won't be static until you first put something into the Session collection. Like so:

    HttpContext.Session.Set("Foo", new byte[] { 1, 2, 3, 4, 5 });
    
    _keyName = HttpContext.Session.Id + "_searchResults";
    

    ASP.NET Core: Session Id Always Changes