Giter Site home page Giter Site logo

aspnetcore.responsecaching.extensions's People

Contributors

alefranz avatar b-w avatar benaadams avatar davidfowl avatar dotnet-maestro[bot] avatar dougbu avatar dylandmitri avatar halter73 avatar jkotalik avatar kahbazi avatar meziantou avatar natemcmaster avatar speige avatar tratcher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

aspnetcore.responsecaching.extensions's Issues

Browser sending max-age=0 server-side caching does not cache

Hi all,

I am initialized the middleware like this:

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<Settings>(Configuration.GetSection("AppSettings"));

            services.Configure<BrotliCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.AddResponseCompression(options =>
            {
                options.Providers.Add<BrotliCompressionProvider>();
                options.Providers.Add<GzipCompressionProvider>();
                options.EnableForHttps = true;
            });

            services.AddMemoryCache();

            services.AddResponseCaching(ignoreBrowserNoCacheNoStore: true);

            services.AddHttpClient();

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            
            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 24 * 365; //365 days
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                        "public,max-age=" + durationInSeconds;
                }
            });

            app.UseRouting();

            app.UseCustomResponseCaching();
                       
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

        }

At the controller action level I put this attribute: [ResponseCache(Duration = 3600)]

When I open the url in chrome by typing it directly on the address bar, it sends max-age=0 header, and that means that the server always generate a new version of the page and never use the cached version.

I have been able to disabled this by adding the line requestMaxAge = TimeSpan.MaxValue; in ResponseCachingPolicyProvider.IsCachedEntryFresh method, just below the line:
HeaderUtilities.TryParseSeconds(requestCacheControlHeaders, CacheControlHeaderValue.MaxAgeString, out requestMaxAge);

But I am sure there is a better way to disable this, in order to send always the server-side cached version of the page.

Thank u!
Best
David

Null Ref Exception CustomResponseCachingMiddleware

Hi all,

First of all, thanks for your effort by creating this package to improve .NET Core native ResponseCache.

I am testing this for one of our new projects in order to apply server-side caching to our web pages. I am getting a null exception error when initializing the response cache like this:

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<Settings>(Configuration.GetSection("AppSettings"));

            services.Configure<BrotliCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;
            });
            services.AddResponseCompression(options =>
            {
                options.Providers.Add<BrotliCompressionProvider>();
                options.Providers.Add<GzipCompressionProvider>();
                options.EnableForHttps = true;
            });

            services.AddMemoryCache();

            services.AddResponseCaching(ignoreBrowserNoCacheNoStore: true);

            services.AddHttpClient();

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            
            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 24 * 365; //365 days
                    ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                        "public,max-age=" + durationInSeconds;
                }
            });

            app.UseRouting();

            app.UseCustomResponseCaching();
                       
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

        }

Look at the lines services.AddResponseCaching(ignoreBrowserNoCacheNoStore: true); in ConfigureServices and app.UseCustomResponseCaching(); in Configure methods.

With that initialization, I get null exception in the constructor of CustomResponseCachingMiddleware:

public CustomResponseCachingMiddleware(RequestDelegate next, IOptions<ResponseCachingOptions> responseCachingOptions, IOptions<CustomResponseCachingOptions> overridableResponseCachingOptions, ILoggerFactory loggerFactory, IResponseCachingPolicyProvider policyProvider, IResponseCachingKeyProvider keyProvider) : 
base(next, responseCachingOptions, loggerFactory, policyProvider, overridableResponseCachingOptions.Value.ResponseCacheFactory(responseCachingOptions), keyProvider)
    {
    }

The exception is due to overridableResponseCachingOptions.Value.ResponseCacheFactory coming null for this ResponseCache implementation.

I am modified constructor to this:

        public CustomResponseCachingMiddleware(RequestDelegate next,
            IOptions<ResponseCachingOptions> responseCachingOptions,
            IOptions<CustomResponseCachingOptions> overridableResponseCachingOptions,
            ILoggerFactory loggerFactory,
            IResponseCachingPolicyProvider policyProvider,
            IResponseCachingKeyProvider keyProvider,
            IMemoryCache _memoryCache) :
            base(next, responseCachingOptions, loggerFactory, policyProvider,
            GetResponseCache(responseCachingOptions, overridableResponseCachingOptions, _memoryCache),
            keyProvider)
        {
        }

        private static IResponseCache GetResponseCache(IOptions<ResponseCachingOptions> responseCachingOptions,
            IOptions<CustomResponseCachingOptions> overridableResponseCachingOptions, IMemoryCache _memoryCache)
        {

            return overridableResponseCachingOptions.Value.ResponseCacheFactory == null ?
                new MemoryResponseCache(_memoryCache) :
                overridableResponseCachingOptions.Value.ResponseCacheFactory(responseCachingOptions);

        }


    }

So now I check if overridableResponseCachingOptions.Value.ResponseCacheFactorycomes null and then instantiate a new MemoryResponseCache implementation.
But I am sure this is not the correct way to do this, so maybe I am doing something wrong in the initialization and that's the reason overridableResponseCachingOptions.Value.ResponseCacheFactory is coming null.

Maybe anyone could help on this?

Thank you!
Best regards
David

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.