方案一:全局,默认是有缓存,这里设置取消缓存
app.UseStaticFiles(new StaticFileOptions()
{
OnPrepareResponse = context =>
{
//context.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "no-cache";//不做本地缓存,但会对比服务器上的文件的摘要
context.Context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "no-store";//完全不做存储缓存,每次f5刷新都是获取最新数据
}
});
方案二:缓存指定的action
public IActionResult Index()
{
//缓存当前action
base.HttpContext.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "public,max-age=3600";
return View();
}
方案三:缓存指定的action
[ResponseCache(Duration =3600)]//缓存当前action
public IActionResult Index()
{
return View();
}
方案四:自定义
public class MyCacheFilterAttribute : Attribute, IActionFilter, IFilterMetadata
{
public int Duration { get; set; }
public void OnActionExecuted(ActionExecutedContext context)
{
int timesecond=this.Duration==0 ? 60 : this.Duration;
context.HttpContext.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = $"public,max-age={timesecond}";
}
public void OnActionExecuting(ActionExecutingContext context)
{
//throw new NotImplementedException();
}
}
应用:
[MyCacheFilter(Duration =60)]
public IActionResult Index()
{
return View();
}