Solved: app.UseStaticFiles( ... ) - where/when to call?
k
I need to call
app.UseStaticFiles( ... )
to customize the behavior, but I don't know where/when to put this in
Program.cs
. I'm guessing
.UseUmbraco()
already does this internally? I'm using the Umbraco 13 NuGet project template.
It seems to work when calling it after
UseUmbraco
, but I'm worried I'm changing some default behavior Umbraco relies on.
d
Hey, it's usually not recommended to add your own call to
.UseStaticFiles()
, however, there is an extension point where you can modify the settings! You can implement
IConfigureOptions<StaticFileOptions>
. I use this to add response cache headers to the output like this:
Copy code
csharp
public class CachingStaticFileOptionsConfiguration : IConfigureOptions<StaticFileOptions>
{
    public void Configure(StaticFileOptions options)
    {
        options.OnPrepareResponse = ctx =>
        {
            // exclude requests to backoffice resources,
            //    because they already have finetuned headers
            if (IsUmbracoRequest(ctx.Context))
            {
                return;
            }

            Microsoft.AspNetCore.Http.Headers.ResponseHeaders headers = ctx.Context.Response.GetTypedHeaders();
            headers.CacheControl = new CacheControlHeaderValue
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(Defaults.StaticAssetResponseCacheDuration),
                Extensions =
                    {
                        new NameValueHeaderValue("immutable")
                    }
            };
        };
    }

    private static bool IsUmbracoRequest(HttpContext context)
    {
        return context.Request.Path.StartsWithSegments("/umbraco");
    }
}
Would that work for you?
I register it in a composer like this:
Copy code
csharp
builder.Services.ConfigureOptions<CachingStaticFileOptionsConfiguration>();
k
Wow, thanks! This looks perfect. Do you know where I can find the recommendation to not call
UseStaticFiles()
? I didn't find anything when searching.
d
Ah no, bad phrasing excuse me. It's in my experience a bad idea to call it yours3lf. Have had difficult to track down issues when adding the middleware myself
Especially image cropping doesn't work when you add the middleware yourself
b
I never had issues with usage of UseStaticFiles, and i made not one package using it 🤔, so not sure what was your experience but there shouldn't be issue to call it even 1000 times in different places 🤔
k
Can you tell me more about you "made not one package using it"?
b
Mostly it was internal company framework packaged, so can't go in details sorry, but yeah I am usually person to find weird issues
76 Views