Saturn icon indicating copy to clipboard operation
Saturn copied to clipboard

Cache-Control for static files

Open BennieCopeland opened this issue 5 years ago • 1 comments

Setting the Cache-Control header for static files is a pretty common thing to do, but there is no option when using use_static to set it. I worked around this using the following code, but it also requires me to duplicate setting the web root path. Is there a better way to do this out of the box?

type CacheControl =
    | NoCacheControl
    | CacheControl of string
    
let useStaticFiles cache (app : IApplicationBuilder) =
    match cache with
    | NoCacheControl ->
        app.UseStaticFiles()
    | CacheControl value ->
        let handler (ctx : StaticFileResponseContext) =
            ctx.Context.Response.Headers.Append("Cache-Control", StringValues(value))
            |> ignore
            
        let action = System.Action<StaticFileResponseContext>(handler)
        
        app.UseStaticFiles(StaticFileOptions(OnPrepareResponse = action))

let setWebRootPath path (builder : IWebHostBuilder) =
    let p = Path.Combine(Directory.GetCurrentDirectory(), path)
    builder.UseWebRoot(p)

let app = application {
    use_router Router.appRouter
    app_config (useStaticFiles (CacheControl "public, max-age=604800"))
    webhost_config (setWebRootPath "static")
    memory_cache
}

BennieCopeland avatar Aug 24 '20 11:08 BennieCopeland

Yes, currently use_static doesn't support any additional options. We should look into adding additional overload here that will enable customizations of it.

Krzysztof-Cieslak avatar Sep 01 '20 12:09 Krzysztof-Cieslak