2017年6月3日 星期六

[ASP.NET Core] Response caching

 ASP.NET Core   Response Caching 


Introduction


In HTTP 1.1, we can use Cache-Control header to define the response caching strategy.
We will learn how to use it thru the following common cache directives.

1.  no-cache

2.  public
Specify that the response is cacheable by clients and shared (proxy) caches.

3.  private
specify that the response is cacheable only on the client and not by shared (proxy server) caches.

See more information about the difference between private and public Cache-Control.


Environment


.NET Core 2.0.0 preview 1



Implement


Register service

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     services.AddResponseCaching();
}


No-Cache

[ResponseCache(Location = ResponseCacheLocation.None)] 
[Route("[action]/{name}")]
public IActionResult Index(string name)
{
     ViewBag.CurrentDatetime = $"Hello, {name}, it's {DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")} now";
     LogUtility.Logger.Debug($"Create Index response...");
     return View();
}

We can set NoStore to true for preventing caching on some browser’s behavior.

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]


Result





Public Cache

[ResponseCache(Duration = 120)]//Cache-Control:public
[Route("[action]")]
public IActionResult Help()
{
    LogUtility.Logger.Debug($"Create Help response...");
    return View();
}


Result




Demo






Private Cache

[ResponseCache (Duration = 120, Location = ResponseCacheLocation.Client)]
[Route("[action]/{name}")]
public IActionResult Index(string name)



Result




Demo





Cache Profiles

We can also set cache profiles in ConfigureServices for reusing the settings.



Startup.cs

public void ConfigureServices(IServiceCollection services)
{
       services.AddMvc((options) =>
                options.CacheProfiles.Add("default", new CacheProfile()
                {
                    Duration = 60,
                    Location = ResponseCacheLocation.Client
                })
            );
            services.AddResponseCaching();
}


Use it with ResponseCache

[ResponseCache(CacheProfileName = "default")]  //Using CacheProfileName
[Route("[action]/{name}")]
public IActionResult Index(string name)




Reference








沒有留言:

張貼留言