using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; namespace SlpModularCms.Core.Hosting.Website; /// Registration of the prerendered-website serving (only used when ). public static class PrerenderedSiteExtensions { /// Text types compressed on the website (same list as the site's nginx configuration). internal static readonly string[] CompressibleMimeTypes = [ "text/html", "text/css", "text/plain", "text/xml", "text/javascript", "application/javascript", "application/json", "application/xml", "image/svg+xml" ]; public static IServiceCollection AddCmsWebsite(this IServiceCollection services, IConfiguration configuration) { services.AddOptions() .Bind(configuration.GetSection(WebsiteOptions.SectionName)) .Validate(o => WebsiteOptions.IsValidLogLevel(o.LogLevel), "Website:LogLevel must be a log level name (Trace, Debug, Information, Warning, Error, Critical, None) or empty.") .ValidateOnStart(); // Website:LogLevel (env: Website__LogLevel) sets the level of the website's logger category. It exists // because Logging__LogLevel__SlpModularCms.Website has a dot in its name, which systemd's // EnvironmentFile does not accept. var configuredLevel = configuration[$"{WebsiteOptions.SectionName}:LogLevel"]; if (!string.IsNullOrWhiteSpace(configuredLevel) && Enum.TryParse(configuredLevel.Trim(), ignoreCase: true, out var level)) { services.AddLogging(logging => logging.AddFilter(PrerenderedSiteMiddleware.LoggerCategory, level)); } // Fills CMS content and the instance's own address into the pages it serves (see HtmlMarkerInjector). services.AddSingleton(); services.AddSingleton(provider => provider.GetRequiredService()); // The shared CMS data block of the pages (siteUrl plus what each module contributes). services.TryAddEnumerable(ServiceDescriptor.Scoped()); // Presence of the marker switches on the full security-header set for website responses. services.AddSingleton(); services.AddSingleton(provider => { var environment = provider.GetRequiredService(); var webRoot = environment.WebRootPath ?? Path.Combine(environment.ContentRootPath, "wwwroot"); return new WebsiteFileAccess( Path.Combine(webRoot, StaticContentExtensions.WebsiteDirectoryName), provider.GetRequiredService().CreateLogger(PrerenderedSiteMiddleware.LoggerCategory)); }); // Lets the catch-all 404 route refuse the reserved prefixes (see NotReservedPathConstraint). services.Configure(options => options.ConstraintMap[NotReservedPathConstraint.Name] = typeof(NotReservedPathConstraint)); // gzip only, like nginx today; Brotli is deliberately not registered. services.AddResponseCompression(options => { options.Providers.Add(); options.MimeTypes = CompressibleMimeTypes; }); return services; } /// /// Compression (non-reserved paths only) and the website middleware. Replaces the website static /// mount of SpaFallback mode; place it where UseCmsStaticContent sits. /// public static WebApplication UseCmsPrerenderedSite(this WebApplication app) { app.UseWhen( context => !WebsitePathResolver.IsReservedPath(context.Request.Path.Value), branch => branch.UseResponseCompression()); app.UseMiddleware(); return app; } /// Maps the final fallback that serves 404.html with status 404. public static WebApplication MapCmsWebsiteNotFound(this WebApplication app) { // An explicit pattern: the default fallback pattern carries the "nonfile" constraint, and a // missing asset (/assets/x.js) must also get the 404 page, not a bare framework 404. The // reserved prefixes are excluded so they keep their own behaviour (see NotReservedPathConstraint). app.MapFallback($"{{*path:{NotReservedPathConstraint.Name}}}", WebsiteNotFoundHandler.HandleAsync); return app; } }