ASP.NET Core中提供了ResponseCacheAttribute来实现缓存,它的定义如下:
[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; }
}
其中,ResponseCacheLocation定义了缓存的位置,是重点:
// 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
}
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());