Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34170

How to introduce more extensions to UseStaticFiles

I'm using Asp.Net Core 2.2, and I always use the following code as cache control for static files:

var cachePeriod = env.IsDevelopment() ? "600" : "2592000";
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
    }
}); 

However this time I'm also using .webp images, and I notice that caching is not working for this extension. How can I add extensions to be used by UseStaticFiles()?

Upvotes: 2

Views: 917

Answers (1)

Brian Deragon
Brian Deragon

Reputation: 2967

The Cache-Control header controls caching at the request level. So any file served as a response to a request from UseStaticFiles will get cached.

The problem here is, UseStaticFiles doesn't recognize the mime-type of webp as one handled by the StaticFileHandler, you can fix this by either using FileExtensionContentTypeProvider and giving it a mime-type IIS understands as a StaticFile and passing that provider into the StaticFileOptions or by allowing IIS to serve unknown file types (less secure, but easier/faster):

var cachePeriod = env.IsDevelopment() ? "600" : "2592000";
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
    },
    ServeUnknownFileTypes = true

);

See Static files in ASP.NET Core for more information on adding the mime type using FileExtensionContentTypeProvider. Also reference Adding Static Content MIME Mappings for an example of how to modify your web.config to map .webp file extensions to the staticContent (Static File Handler) file handler.

Upvotes: 3

Related Questions