AnderssonPeter / CompressedStaticFiles

asp.net core middleware to send compressed static files to the browser without having to compress on demand, also has support for sending more advanced image formats when the browser indicates that i has support for it.
Apache License 2.0
88 stars 18 forks source link

Unable to specify caching due to OnPrepareResponse being overwritten #7

Closed lukerogers closed 7 years ago

lukerogers commented 7 years ago

If you try to pass in StaticFileOptions that include setting the caching headers, they don't work since a new delegate is created. For example, if you pass in

app.UseCompressedStaticFiles(new StaticFileOptions
{
  OnPrepareResponse = ctx =>
  {
    if (env.IsDevelopment()) return;
    const int durationInSeconds = 60 * 60 * 24;
    ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds;
    ctx.Context.Response.Headers[HeaderNames.Vary] = HeaderNames.AcceptEncoding;
  }
});

It won't work because it is overwritten in CompressedStaticFileMiddleware.cs

staticFileOptions.Value.OnPrepareResponse = ctx =>
{
  foreach (var compressionType in compressionTypes.Keys)
  {
    var fileExtension = compressionTypes[compressionType];
    if (ctx.File.Name.EndsWith(fileExtension, StringComparison.OrdinalIgnoreCase))
    {
      string contentType = null;
      if (contentTypeProvider.TryGetContentType(ctx.File.PhysicalPath.Remove(ctx.File.PhysicalPath.Length - fileExtension.Length, fileExtension.Length), out contentType))
        ctx.Context.Response.ContentType = contentType;
      ctx.Context.Response.Headers.Add("Content-Encoding", new[] { compressionType });
    }
  }
};

The original value needs to be stored and invoked.

I created a pull request that addresses this issue #6 Adding ability to execute OnPrepareResponse that is passed in

AnderssonPeter commented 7 years ago

Sorry for the slow response, i have merged and published a new nuget package. But sadly i don't have the environment to verify that it works so could you check it out and close this if it works as intended.

lukerogers commented 7 years ago

It works for me.