aspnet / StaticFiles

[Archived] Middleware for handling requests for file system resources including files and directories. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
114 stars 72 forks source link

Response cache not working #171

Closed Flood closed 7 years ago

Flood commented 7 years ago

I'm trying to add Cache-Control header to all my static files using this in my startup.cs

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = (context) =>
    {
        const int durationInSeconds = 2592000; //30 days
        context.Context.Response.Headers.Append("Cache-Control", "max-age=" + durationInSeconds);
        context.Context.Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
    }
});

But the Cache-Control header is not set to either images, js or css files.

Anyone that have successfully implemented this?

I'm running an Angular 2 application on the front and using ASP.NET 5 as the 'core'. Can they interfere or something?

mcgiany commented 7 years ago

I got same issue in my ASP Net Core project. I try this:

app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                    {
                        var headers = context.Context.Response.GetTypedHeaders();
                        headers.CacheControl = new CacheControlHeaderValue
                        {
                            MaxAge = TimeSpan.FromDays(5),
                            Private = true
                        };
                    }
            });
Flood commented 7 years ago

I don't think you can have "Private = true", it must be public.

I have also tried these without luck:

context.Context.Response.Headers.Add("Cache-Control", "public, max-age=2592000")

context.Context.Response.Headers[HeaderNames.CacheControl] = new string[] { "public,max-age=2592000" };

context.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=31536000" });
Flood commented 7 years ago

This one seems to work:

context.Context.Response.Headers.Append("Cache-Control", "public, max-age=2592000");

mcgiany commented 7 years ago

I fix it by moving UseStaticFiles above the UseIdentity.