c# .net core 设置缓存

1、开启ResponseCaching的缓存(ResponseCaching相当于老版本的OutPutCache):

  在Startup.cs文件中设置:

        public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCaching();
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCaching();

  正常使用:

        [ResponseCache(Duration = )]
public ActionResult GetHotel(HotelListRequest request)
{

  设置ResponseCaching的策略,供多个Controller使用:

       services.AddMvc(option => {
option.CacheProfiles.Add("CacheFile", new CacheProfile()
{
Duration = ,
});
option.CacheProfiles.Add("NoStore", new CacheProfile()
{
Location = ResponseCacheLocation.None,
NoStore = true
});
});

  使用策略:

        [ResponseCache(CacheProfileName = "CacheFile")]
public ActionResult GetHotel(HotelListRequest request)
{

2、开启静态资源缓存:

  在Startup.cs文件中设置:

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
const int durationInSeconds = * * ;
ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds;
}
});

3、指定某个方法设置缓存,可以通过自定义过滤器实现:

  创建过滤器:

    public class NeedCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context); context.HttpContext.Response.Headers[HeaderNames.LastModified] = "2018-05-28 14:00:00";
context.HttpContext.Response.Headers[HeaderNames.Expires] = "2018-05-28 16:00:00"; }
}

  使用:

        [NeedCache]
public ActionResult GetHotel(HotelListRequest request)

4、方法中直接写代码实现:

HttpContext.Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = TimeSpan.FromSeconds()
};
Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };

注意:1、以上方式是通过设置浏览器的过期时间实现缓存,此方式仅适用于Ajax请求且Get请求,Post请求和非Ajax请求暂不支持,目前测试结果是这样的。

上一篇:[Coding Study]——目录


下一篇:在Servlet的GenericServlet类中为什么有两个init()方法