#Solved: app.UseStaticFiles( ... ) - where/when to call?

1 messages · Page 1 of 1 (latest)

winter sun
#

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.

#

app.UseStaticFiles( ... ) - where/when to call?

#

It seems to work when calling it after UseUmbraco, but I'm worried I'm changing some default behavior Umbraco relies on.

warped sphinx
#

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:

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:

builder.Services.ConfigureOptions<CachingStaticFileOptionsConfiguration>();
winter sun
#

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.

warped sphinx
#

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

winter sun
#

Solved: app.UseStaticFiles( ... ) - where/when to call?

versed tartan
#

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 🤔

winter sun