【发布时间】:2021-12-25 07:36:37
【问题描述】:
我有一个带有 EF 的 .Net Core 应用程序,它返回一个名为 Customer 的页面作为主页。但是当用户尝试在假期访问应用程序(假期列表存储在表格中)而不是客户页面时,我需要显示一个应用程序不可用页面(AppNotAvialable.cshmtl)。我不是每次访问主页时都查询假期列表表,而是尝试使用内存缓存,以便我可以将查询响应存储在缓存中并在控制器中使用它们。我是第一次实现缓存,下面是我尝试过的
public class CustomersController : Controller
{
private readonly SurplusMouseContext _context;
private readonly IMemoryCache memoryCache;
.......................
public async Task<IActionResult> Index(string sortOrder, string searchString,
int? pageNumber, string currentFilter)
{
int holidaycheck;
var timeUtc = DateTime.UtcNow;
var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var todayDt = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);
bool isExist = memoryCache.TryGetValue("HolidayWk", out holidaycheck);
if (!isExist)
{
holidaycheck = (from hc in _context.HolidayWeeks
where hc.HolidateDate.Date == todayDt.Date
select hc).Count();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(2));
memoryCache.Set("HolidayWk", holidaycheck, cacheEntryOptions);
}
if (holidaycheck != 0)
{
return View("/Views/Customers/AppNotAvailable.cshtml");
}
else
{
当我尝试调试应用程序时,它会抛出如下错误
任何人都可以建议我是否在这里实现内存缓存正确/遗漏任何东西以及我应该在哪里做cacheMemory.Remove()任何帮助非常感谢
【问题讨论】:
-
你实例化
MemoryCache实例了吗? -
你是不是在startup.cs中绑定了对象,然后在构造函数中使用?
标签: asp.net-core .net-core caching entity-framework-core asp.net-core-mvc