using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; namespace Kit.Helpers.Config; public class StaticFileConfigBuilder where TIApplicationBuilder : IApplicationBuilder { private readonly List _contentModules; private Action _onPrepareResponse; internal StaticFileConfigBuilder() { _contentModules = new List(); _onPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=3600"); }; } public StaticFileConfigBuilder WithContentModule(string moduleName) { _contentModules.Add(moduleName); return this; } public StaticFileConfigBuilder WithOnPrepareResponse(Action ctx) { _onPrepareResponse = ctx; return this; } internal TIApplicationBuilder Apply(TIApplicationBuilder app) { IWebHostEnvironment env = app.ApplicationServices.GetRequiredService(); // основной wwwroot List fileProviderItems = new List { env.WebRootFileProvider }; if (_contentModules.Count > 0) { #if DEBUG fileProviderItems.Add(new PhysicalFileProvider(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot"))); #else fileProviders.AddRange(_contentModules.Select(moduleName => new PhysicalFileProvider(Path.Combine(_env.ContentRootPath, "wwwroot", "_content", moduleName)))); #endif } var fileProvider = new CompositeFileProvider(fileProviderItems); env.WebRootFileProvider = fileProvider; app.UseStaticFiles(new StaticFileOptions { FileProvider = fileProvider, RequestPath = "", OnPrepareResponse = _onPrepareResponse }); return app; } } public static class StaticFileConfigBuilderExt { public static TIApplicationBuilder UseCustomStaticFiles(this TIApplicationBuilder app, Action> options) where TIApplicationBuilder : IApplicationBuilder { var config = new StaticFileConfigBuilder(); if (options != null) options(config); config.Apply(app); return app; } }