question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cannot Override Cache Control Header.

See original GitHub issue

I am using aspnetboilerplate version 5.13.0. I want response cache but it didn’t work no matter what i tried. Response Header has always cache-control: no-cache, no-store.

I tried the following;

  • I just added the response cache attribute.
  • Response Cache middleware and cache profile.
  • I defined DefaultResponseCacheAttributeForControllers in WebCoreModule PreInitialize

Offical Documentation;

    Abp provides a convenient way for you to configure the default Cache-Control header for all ApplicationService and Controller via IAbpAspNetCoreConfiguration
    
    DefaultResponseCacheAttributeForAppServices: Used if Controller class does not define Microsoft.AspNetCore.Mvc.ResponseCacheAttribute
    DefaultResponseCacheAttributeForControllers: Used if ApplicationService class does not define Microsoft.AspNetCore.Mvc.ResponseCacheAttribute
    Note: Cache-Control is not configured by default. You may configure for all ApplicationService and Controller then use Microsoft.AspNetCore.Mvc.ResponseCacheAttribute at method/action level to override it.

Does anyone have a code sample? Because I couldn’t work correctly.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
onur-ardalcommented, Jun 21, 2021

@ismcagdas as follows,


[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public async Task<IActionResult> PrivacyPolicy()
        {
            var model = new BasePageModel();
            return View(model);
        }

Startup;

public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCaching();
            services.AddResponseCompression(options =>
            {
                options.EnableForHttps = true;
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
                                         {
                                            // General
                                            "text/plain",
                                            "image/svg+xml",
                                            // Static files
                                            "text/css",
                                            "application/javascript",
                                            // MVC
                                            "text/html",
                                            "application/xml",
                                            "text/xml",
                                            "application/json",
                                            "text/json",
                            }); ;
                options.Providers.Add<GzipCompressionProvider>();
            });
            services.AddHttpClient();
            services.AddHttpContextAccessor();
            // MVC
            services.AddControllersWithViews(
                    options =>
                    {
                        options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
                        options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
                    }
                )
                .AddRazorRuntimeCompilation()
                .AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
                    {
                        NamingStrategy = new CamelCaseNamingStrategy()
                    };
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                });

            services.AddAuthentication(
                    CertificateAuthenticationDefaults.AuthenticationScheme)
                .AddCertificate();

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);


            services.Configure<RequestLocalizationOptions>(options =>
            {
                options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("tr-TR");
                options.SupportedCultures = new List<CultureInfo> { new CultureInfo("tr-TR") };
                options.RequestCultureProviders.Clear();
            });
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "Client";
            });

            services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequiredUniqueChars = 0;
            });

            services.AddScoped<IWebResourceManager, WebResourceManager>();
            services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Fastest;

            });

            return services.AddAbp<WebMvcModule>(
                options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                )
            );
        }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {

            app.UseAbp(); // Initializes ABP framework.
            app.UseResponseCompression();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseStatusCodePagesWithReExecute("/{0}");
            }
            app.UseHttpsRedirection();

            app.UseStaticFiles(new StaticFileOptions
            {

                OnPrepareResponse = ctx =>
                {
                    const int durationInSeconds = 60 * 60 * 24 * 15;
                    // using Microsoft.AspNetCore.Http;
                    ctx.Context.Response.Headers.Append(
                         "Cache-Control", $"public, max-age={durationInSeconds}");
                }
            });
            app.UseRouting();
            app.UseAuthentication();
            app.UseJwtTokenMiddleware();
            app.UseAuthorization();
            app.UseRequestLocalization();
            app.UseResponseCaching();
            app.UseEndpoints(endpoints =>
            {
                //endpoints.MapHub<AbpCommonHub>("/signalr");
                endpoints.MapCustomRoutes(app, _appConfiguration);
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    "image",
                    "smart/{*imagePath}/",
                    new { controller = "Home", action = "ResizedImage" }
                    );
                endpoints.MapControllerRoute("routeList", "routeList",
                    new { controller = "Home", action = "ClearRouteListCache" });
            });


        }

CoreModule;

public class WebCoreModule : AbpModule
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfigurationRoot _appConfiguration;

        public WebCoreModule(IWebHostEnvironment env)
        {
            _env = env;
            _appConfiguration = env.GetAppConfiguration();
        }

        public override void PreInitialize()
        {
            Configuration.DefaultNameOrConnectionString = _appConfiguration.GetConnectionString(
                Consts.ConnectionStringName
            );
            Configuration.Modules.AbpAspNetCore().DefaultResponseCacheAttributeForControllers = new Microsoft.AspNetCore.Mvc.ResponseCacheAttribute()
            {
                Duration = 30,
                Location = Microsoft.AspNetCore.Mvc.ResponseCacheLocation.Any,
                NoStore = false,
            };
      }
}

image

0reactions
ismcagdascommented, Aug 9, 2021

@onur-ardal I think the problem is related to anti-forgery cookie, see the Notes section of https://docs.microsoft.com/en-us/aspnet/core/performance/caching/middleware?view=aspnetcore-5.0#conditions-for-caching. When I remove the AbpAntiForgeryManager.SetCookie(Context); I can set Cache-Control response header. So, it seems like this is by design of ASP.NET Core.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Override the "cache-control" values in a HTTP response
In no way. The Cache-Control (and other) response headers can be changed, but it will only be visible in the getResponseHeader method.
Read more >
Cache-Control - HTTP - MDN Web Docs
The Cache-Control HTTP header field holds directives (instructions) — in both requests and responses — that control caching in browsers and ...
Read more >
Cache-Control header being overridden by Cloudflare
So I set a page rule that covers my whole site and enabled Origin Cache Control, and now it seems to work. I...
Read more >
Cache-Control - How to Properly Configure It
The "s" stands for shared and is relevant only to CDNs or other intermediary caches. This directive overrides the max-age and expires header....
Read more >
Spring Security - Cache Control Headers
To do this, let's try overriding the cache control headers in a single handler method, by use of the CacheControl cache.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found