简体   繁体   中英

Associate class instance to Session in asp.net core

I'm currently working on a webserver in asp.net core. I want the server to process the users input and data and am looking for a good solution to save complex Objects for the runtime.

So my first approach was to use Sessions. In Asp.net, sessions used to work like Session["key"] = new ValueObject()

In asp.net core however you can only use the methods SetString, SetInt32 and Set for byte arrays. I found a lot of solutions which basically converted the objects into Json strings. However in my case this isn't possible due to the objects containing other object references and more.

My second idea was to create a list of objects with the SessionId as identifier. Problem with this is that every time I would make request to the server, it needs to go through all existing Sessions to find the matching one, so this would probably drastically increase the time for the request.

So my question is what would be the best way to save user related objects?

Is using Sessions even the best way for solving this problem or am I missing something?

Note: Request are handled by JQuery AJAX, so reloading the page for accessing data is not an option.

You could try using the MemoryCache that can hold any .net type. It is not a problem but given it is a shared structure, it will be shared to all users, so, you have to carefull manage it. To do it, you could use HttpContext.Session.Id to define the keys on the memory cache instance. For sample (pseudo-code I didn't test):

public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }    

    public async Task<IActionResult> CacheGetOrCreateAsynchronous()
    {
        string cacheKey = $"{HttpContext.Session.Id}_data";

        var cacheEntry = await
            _cache.GetOrCreateAsync(cacheKey , entry =>
            {
                entry.SlidingExpiration = TimeSpan.FromSeconds(3);
                return Task.FromResult(DateTime.Now);
            });

        return View("Cache", cacheEntry);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM