ASP.NET Core中的Http缓存使用 |
|
而 了解Http缓存
强缓存 强缓存是指缓存命中时,客户端不会向服务器发请求,浏览器 Expires - 绝对时间 示例: Cache-Control - 相对时间/更多控制 绝对时间是一个绝对时间,因为计算时不方便;而且服务端是依据服务器的时间来返回,但客户端却需要依据客户的时间来判断,因此也容易失去控制 。
其中最有意思的要数
而 协商缓存 协商缓存是指缓存命中时,服务器返回 在要精细控制时,协商缓存比强缓存更有用,它有 Last-Modified/If-Modify-Since(对比修改时间) 示例:
ETag/If-None-Match(对比校验码)
清缓存要点
ASP.NET Core的Http缓存
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class ResponseCacheAttribute : Attribute, IFilterFactory, IFilterMetadata, IOrderedFilter
{
public ResponseCacheAttribute();
public string CacheProfileName { get; set; }
public int Duration { get; set; }
public bool IsReusable { get; }
public ResponseCacheLocation Location { get; set; }
public bool NoStore { get; set; }
public int Order { get; set; }
public string VaryByHeader { get; set; }
public string[] VaryByQueryKeys { get; set; }
}
其中,
// Determines the value for the "Cache-control" header in the response.
public enum ResponseCacheLocation
{
// Cached in both proxies and client. Sets "Cache-control" header to "public".
Any = 0,
// Cached only in the client. Sets "Cache-control" header to "private".
Client = 1,
// "Cache-control" and "Pragma" headers are set to "no-cache".
None = 2
}
注意看源文件中的注释, 注意 其中 另外可以通过 不要误会,所有 如果不想缓存,则设置 注意单独设置 示例1 这是一个很典型的使用示例:
public class HomeController : Controller
{
[ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Client)]
public IActionResult Data()
{
return Json(DateTime.Now);
}
}
我定义了
using var http = new HttpClient();
var resp1 = await http.GetAsync("https://localhost:55555/home/data");
Console.WriteLine(resp1.Headers.CacheControl.ToString());
Console.WriteLine(await resp1.Content.ReadAsStringAsync());
输入结果如下:
另外, CacheProfileName示例 另外,如果需要共用缓存配置,可以使用
.ConfigureServices(s =>
{
s.AddControllers(o =>
{
o.CacheProfiles.Add("3500", new CacheProfile
{
Duration = 3500,
Location = ResponseCacheLocation.Client,
});
});
});
这样我就定义了一个名为
public class HomeController : Controller
{
[ResponseCache(CacheProfileName = "3500")]
public IActionResult Data()
{
return Json(DateTime.Now);
}
}
总结
但
有机会我会具体聊聊这些缓存 。 到此这篇关于ASP.NET Core中的Http缓存使用的文章就介绍到这了,更多相关ASP.NET Core Http缓存内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! |