Skip to content

Cache-Control for static files #271

@BennieCopeland

Description

@BennieCopeland

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
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions