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 = 20)]
        public ActionResult GetHotel(HotelListRequest request)
        {

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

       services.AddMvc(option => {
                option.CacheProfiles.Add("CacheFile", new CacheProfile()
                {
                    Duration = 60,
                });
                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 = 60 * 60 * 24;
                    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(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };

 

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

 

转载于:https://www.cnblogs.com/len0031/p/9100897.html

你可能感兴趣的:(c# .net core 设置缓存)