AnderssonPeter/CompressedStaticFiles

Unable to specify caching due to OnPrepareResponse being overwritten

lukerogers opened this issue · 2 comments

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

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.

It works for me.