99 lines
4.8 KiB
C#
99 lines
4.8 KiB
C#
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;
|
|
|
|
/// <summary>Registration of the prerendered-website serving (only used when <see cref="WebsiteMode.PrerenderedPages"/>).</summary>
|
|
public static class PrerenderedSiteExtensions
|
|
{
|
|
/// <summary>Text types compressed on the website (same list as the site's nginx configuration).</summary>
|
|
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<WebsiteOptions>()
|
|
.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<LogLevel>(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<HtmlMarkerInjector>();
|
|
services.AddSingleton<IIndexHtmlCache>(provider => provider.GetRequiredService<HtmlMarkerInjector>());
|
|
|
|
// The shared CMS data block of the pages (siteUrl plus what each module contributes).
|
|
services.TryAddEnumerable(ServiceDescriptor.Scoped<IHtmlPageTransform, CmsDataBlockTransform>());
|
|
|
|
// Presence of the marker switches on the full security-header set for website responses.
|
|
services.AddSingleton<WebsiteHostingMarker>();
|
|
|
|
services.AddSingleton(provider =>
|
|
{
|
|
var environment = provider.GetRequiredService<IWebHostEnvironment>();
|
|
var webRoot = environment.WebRootPath ?? Path.Combine(environment.ContentRootPath, "wwwroot");
|
|
|
|
return new WebsiteFileAccess(
|
|
Path.Combine(webRoot, StaticContentExtensions.WebsiteDirectoryName),
|
|
provider.GetRequiredService<ILoggerFactory>().CreateLogger(PrerenderedSiteMiddleware.LoggerCategory));
|
|
});
|
|
|
|
// Lets the catch-all 404 route refuse the reserved prefixes (see NotReservedPathConstraint).
|
|
services.Configure<RouteOptions>(options =>
|
|
options.ConstraintMap[NotReservedPathConstraint.Name] = typeof(NotReservedPathConstraint));
|
|
|
|
// gzip only, like nginx today; Brotli is deliberately not registered.
|
|
services.AddResponseCompression(options =>
|
|
{
|
|
options.Providers.Add<GzipCompressionProvider>();
|
|
options.MimeTypes = CompressibleMimeTypes;
|
|
});
|
|
|
|
return services;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Compression (non-reserved paths only) and the website middleware. Replaces the website static
|
|
/// mount of <c>SpaFallback</c> mode; place it where <c>UseCmsStaticContent</c> sits.
|
|
/// </summary>
|
|
public static WebApplication UseCmsPrerenderedSite(this WebApplication app)
|
|
{
|
|
app.UseWhen(
|
|
context => !WebsitePathResolver.IsReservedPath(context.Request.Path.Value),
|
|
branch => branch.UseResponseCompression());
|
|
|
|
app.UseMiddleware<PrerenderedSiteMiddleware>();
|
|
|
|
return app;
|
|
}
|
|
|
|
/// <summary>Maps the final fallback that serves <c>404.html</c> with status 404.</summary>
|
|
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;
|
|
}
|
|
}
|