ارتقاء به ASP.NET Core 1.0 - قسمت 15 - بررسی تغییرات Caching
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۴/۳۰ ۱۴:۴۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
[ResponseCache(Duration = 60)]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
} Cache-Control: public,max-age=60
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View();
} Cache-Control: no-store,no-cache Pragma: no-cache
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.CacheProfiles.Add("PrivateCache",
new CacheProfile
{
Duration = 60,
Location = ResponseCacheLocation.Client
});
}); [ResponseCache(CacheProfileName = "PrivateCache")]
{
"dependencies": {
//same as before
"Microsoft.Extensions.Caching.Memory": "1.0.0"
}, public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache(); [Route("DNT/[controller]")]
public class AboutController : Controller
{
private readonly IMemoryCache _memoryCache;
public AboutController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
[Route("")]
public ActionResult Hello()
{
string cacheKey = "my-cache-key";
string greeting;
if (!_memoryCache.TryGetValue(cacheKey, out greeting))
{
greeting = "Hello";
// store in the cache
_memoryCache.Set(cacheKey, greeting,
new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromMinutes(1)));
}
return Content($"{greeting} from DNT!");
} new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5))
new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromMinutes(5)) .SetAbsoluteExpiration(TimeSpan.FromHours(1))
new MemoryCacheEntryOptions() .SetPriority(CacheItemPriority.NeverRemove))
<cache expires-after="@TimeSpan.FromMinutes(10)">
@Html.Partial("_WhatsNew")
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache expires-after="@TimeSpan.FromSeconds(5)">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache expires-on="@DateTime.Today.AddDays(1).AddTicks(-1)"> <!--View Component or something that gets data from the database--> *last updated @DateTime.Now.ToLongTimeString() </cache>
<cache expires-sliding="@TimeSpan.FromMinutes(5)">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by-user="true">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by-route="id">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by-query="search">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by-cookie="MyAppCookie">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by-header="User-Agent">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by="@ViewBag.ProductId">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache vary-by-user="true" vary-by-route="id">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> <cache expires-sliding="@TimeSpan.FromMinutes(10)"
priority="@Microsoft.Extensions.Caching.Memory.CacheItemPriority.NeverRemove">
<!--View Component or something that gets data from the database-->
*last updated @DateTime.Now.ToLongTimeString()
</cache> app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = context =>
{
context.Context.Response.Headers["Cache-Control"] =
"private, max-age=43200";
context.Context.Response.Headers["Expires"] =
DateTime.UtcNow.AddHours(12).ToString("R");
}
}); <staticContent> <clientCache httpExpires="Sun, 29 Mar 2020 00:00:00 GMT" cacheControlMode="UseExpires" /> </staticContent>
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="1.0.0" />
</ItemGroup>
</Project> services.AddMvc(options =>
{
options.Filters.Add(typeof(NoBrowserCacheAttribute));
});
- برای اینکه مشاهده کنید این فیلتر کار میکند یا نه، باید به برگهی network مرورگر مراجعه کنید و status code نمایش مجدد صفحه را مشاهده کنید:
اثر دکمهی back برای صفحهی لاگینی که کش مرورگر آن توسط فیلتر فوق غیرفعال شده (دریافت مجدد از سرور؛ بجای خوانده شدن از کش مرورگر).
اثر دکمهی back برای یک صفحهی معمولی (از کش مرورگر خوانده شده؛ بجای دریافت مجدد از سرور).
- ضمن اینکه تعریف این فیلتر صرفا برای صفحهی login توصیه میشود و نه جای دیگری و نه کل سایت. گیرم شخصی با دکمهی back، محتوای کش شدهی قبلی را مشاهده کند. مهم نیست. چون بلافاصله با ارسال یک درخواست جدید، فیلتر Authorize، دسترسی او را سد میکند. صفحهی کش شده هم بر اساس دسترسی پیشین او در کش مرورگر وجود دارد. مشاهدهی آن صفحهی قدیمی اهمیتی ندارد؛ چون اطلاعات بعدی به روز شده را باید با گذشت از فیلتر Authorize دریافت کند.
توی متد DisableBrowserCache به همون صورت هست که گفتید، ولی در خروجی فقط مقدار "no-cache" نمایش داده میشه. مقدار Expires رو هم تغییر دادم ولی باز در خروجی -1 نمایش داده شد. هر بار هم متد DisableBrowserCache اجرا میشه. مقدار Order فیلتر رو بصورت منفی هم تنظیم کردم ولی فایده ای نداشت. داره از جای دیگه تنظیم میشه. بیس پروژه هم DNTIdentity هست.
ولی در آخر قسمت cache-control ناقص اعمال میشه ؟
PM> Install-Package DNTCommon.Web.Core
@section content{
<link href=@Url.RouteUrl(new { controller="Home", action="GetCss" ,styles=Model.CssBody}) rel="stylesheet" type="text/css" />
} public class MyMemoryCache
{
public MemoryCache Cache { get; set; }
public MyMemoryCache()
{
Cache = new MemoryCache(new MemoryCacheOptions
{
SizeLimit = 1024
});
}
} Exception: Cache entry must specify a value for Size when SizeLimit is set. at Microsoft.Extensions.Caching.Memory.MemoryCache.SetEntry(CacheEntry entry)
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSize(1)
.SetSlidingExpiration(TimeSpan.FromSeconds(3));
[ResponseCache(Duration = 60)]
public IActionResult GetTime()
{
return Content(DateTime.Now.ToString());
} cache-control: public,max-age=60