我正在將舊版 ASP.NET WebForms 應用程式移植到 Razor。它在 Session 集合中存盤了一個物件。會話存盤現在僅限于 byte[] 或 string。一種技術是將物件序列化并存盤為字串,但有一些警告。另一篇文章建議使用其中一個替代快取選項,因此我嘗試使用 MemoryCache。
為此,作為會話替換,我需要一個對用戶及其會話唯一的鍵名。
我想我會用Session.Id這個,像這樣:
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);
}
}
...但是在測驗時,我看到任何瀏覽器重繪 或頁面鏈接點擊都會生成一個新的Session.Id. 這是有問題的。
是否有另一個內置屬性可以用來識別用戶的會話并用于此鍵名目的?一種通過瀏覽器重繪 和網路應用程式中的點擊保持靜止?
謝謝!
uj5u.com熱心網友回復:
Yiyi You 鏈接到的答案解釋了它 - 在Session.Id您首先將某些內容放入 Session 集合之前,它不會是靜態的。像這樣:
HttpContext.Session.Set("Foo", new byte[] { 1, 2, 3, 4, 5 });
_keyName = HttpContext.Session.Id "_searchResults";
ASP.NET Core:會話 ID 始終更改
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446543.html
