我有一個 ASP.Net MVC 應用程式,它回傳一個名為 Customer 的頁面作為主頁。但是當用戶嘗試在假期(假期串列存盤在表格中)而不是客戶頁面訪問應用程式時,我需要顯示一個應用程式不可用頁面。在啟動時我喜歡下面
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Customers}/{action=Index}/{id?}");
});
現在我創建了一個名為 AppNotAvialable.cshmtl 的新頁面,如果今天在 HolidayWeeks 表中存盤為假日,則嘗試回傳此頁面
public async Task<IActionResult> Index(string sortOrder, string searchString,
int? pageNumber, string currentFilter)
{
var timeUtc = DateTime.UtcNow;
var easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var todayDt = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, easternZone);
var holidaycheck = (from hc in _context.HolidayWeeks
where hc.HolidateDate.Date == todayDt.Date
select hc).Count();
if (holidaycheck != 0)
{
return View("/Views/Customers/AppNotAvailable.cshtml");
}
else
{
// Show customer page
我擔心的是,每次用戶嘗試訪問主頁時,都會對資料庫進行查詢以檢查今天是否為假期。所以我想檢查是否有更好的檢查方法,我是否應該將資料存盤在會話/快取中,以便每次訪問主頁時都不會進行查詢。任何人都可以請建議我該怎么做
uj5u.com熱心網友回復:
如果您的假期有固定日期,例如周六和周日,您可以這樣做。這里只是一個沒有快取的demo,大家可以參考。
模型:
public static class CacheKeys
{
public static string Saturday => "Saturday";
public static string Sunday => "Sunday";
}
控制器:
public async Task<IActionResult> Index(string sortOrder, string searchString,
int? pageNumber, string currentFilter)
{
DayOfWeek wk = DateTime.Today.DayOfWeek;
if (CacheKeys.Saturday == wk.ToString()|| CacheKeys.Sunday == wk.ToString())
{
return View("/Views/Customers/AppNotAvailable.cshtml");
}
else
{
return View("/Views/Customers/WorkDay.cshtml");
}
}
只需判斷一周中的當前日期并結合您的固定假期時間。
當然你可以將資料存放在session/cache中,你可以參考檔案添加。
https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-6.0
uj5u.com熱心網友回復:
將MemoryCache服務添加到服務集合中(此服務快取服務器上的資料):
services.AddMemoryCache();
然后可以通過 DI 使用介面注入IMemoryCache。
//Check if there is a cached holiday vm
if (!memoryCache.TryGetValue("HolidayModelVM", out HolidayModelVM HM))//"HolidayModelVM" is the cache key for the vm
{
//Not present in the cache, we create a new one using the database
HM = new HolidayModelVM
{
//Fetch the actual entity that contains the holiday dates
}
//Cache the VM
_ = memoryCache.Set<HolidayModelVM>("HolidayModelVM", HM, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(4),//Expiration time, when expired, the database will be used to fetch and cache a new version of the data.
SlidingExpiration = TimeSpan.FromHours(2)
});
}
//Do your holiday check using the HolidayModelVM
foreach (DayOfWeek offDay in HM.Holidays) //Holidays is a collection of DayOfWeek enums
{
if (DateTime.UtcNow.DayOfWeek == offDay)
{
return View("/Views/Customers/AppNotAvailable.cshtml");
}
}
return View("CustomerPage");
更新假期資料時,從快取中清除 VM,以便下次有人訪問該頁面時獲取新資料:
memoryCache.Remove("HolidayModelVM");
你也可以像@jeremy-lakeman 建議的那樣將所有這些包裝在一個單例服務中,在那里做所有的快取邏輯,然后注入并獲取它是否是假期并相應地回傳結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354933.html
