Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cache control

How do I set cache control to no store and pragma to no cache?

Currently I get this error when I run my application:

An error occurred while starting the application. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.ResponseCaching.Internal.IResponseCachingPolicyProvider' while attempting to activate 'Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware'.

This is my startup.cs

app.UseResponseCaching();

app.Use(async (context, next) =>
{
    context.Response.GetTypedHeaders().CacheControl =
        new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
        {
            NoStore = true,
            NoCache = true,
        };

    await next();
});

What else do I need to set?

like image 444
JianYA Avatar asked Sep 19 '25 11:09

JianYA


1 Answers

Did you already registered in your ConfigureService like this ?

public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();

    app.UseResponseCaching();

    app.Use(async (context, next) =>
    {
        context.Response.GetTypedHeaders().CacheControl = 
            new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(10)
            };
        context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary] = 
            new string[] { "Accept-Encoding" };

        await next();
    });

    app.UseMvc();
}

Update you can find how to set pragma with this question here

like image 126
Tony Ngo Avatar answered Sep 22 '25 07:09

Tony Ngo