简体   繁体   English

将 class 实例关联到 asp.net 内核中的 Session

[英]Associate class instance to Session in asp.net core

I'm currently working on a webserver in asp.net core.我目前正在 asp.net 核心中的网络服务器上工作。 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.所以我的第一个方法是使用 Sessions。 In Asp.net, sessions used to work like Session["key"] = new ValueObject()在 Asp.net 中,会话曾经像Session["key"] = new ValueObject()

In asp.net core however you can only use the methods SetString, SetInt32 and Set for byte arrays.在 asp.net 内核中,您只能对字节 arrays 使用方法 SetString、SetInt32 和 Set。 I found a lot of solutions which basically converted the objects into Json strings.我发现了很多基本上将对象转换为 Json 字符串的解决方案。 However in my case this isn't possible due to the objects containing other object references and more.但是在我的情况下,这是不可能的,因为对象包含其他 object 引用等等。

My second idea was to create a list of objects with the SessionId as identifier.我的第二个想法是创建一个以 SessionId 作为标识符的对象列表。 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.问题是每次我向服务器发出请求时,它都需要通过所有现有的会话 go 来找到匹配的会话,所以这可能会大大增加请求的时间。

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?使用 Sessions 甚至是解决这个问题的最佳方法还是我错过了什么?

Note: Request are handled by JQuery AJAX, so reloading the page for accessing data is not an option.注意:请求由 JQuery AJAX 处理,因此无法重新加载页面以访问数据。

You could try using the MemoryCache that can hold any .net type.您可以尝试使用可以容纳任何 .net 类型的MemoryCache 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.为此,您可以使用HttpContext.Session.Id来定义 memory 缓存实例上的keys 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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