DRN.Framework.Hosting 0.10.1-preview008

Prefix Reserved
This is a prerelease version of DRN.Framework.Hosting.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package DRN.Framework.Hosting --version 0.10.1-preview008
                    
NuGet\Install-Package DRN.Framework.Hosting -Version 0.10.1-preview008
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DRN.Framework.Hosting" Version="0.10.1-preview008" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DRN.Framework.Hosting" Version="0.10.1-preview008" />
                    
Directory.Packages.props
<PackageReference Include="DRN.Framework.Hosting" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DRN.Framework.Hosting --version 0.10.1-preview008
                    
#r "nuget: DRN.Framework.Hosting, 0.10.1-preview008"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DRN.Framework.Hosting@0.10.1-preview008
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DRN.Framework.Hosting&version=0.10.1-preview008&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=DRN.Framework.Hosting&version=0.10.1-preview008&prerelease
                    
Install as a Cake Tool

master develop Quality Gate Status

Security Rating Maintainability Rating Reliability Rating Vulnerabilities Bugs Lines of Code

DRN.Framework.Hosting

Application shell for DRN web applications with security-first design, structured lifecycle, and type-safe routing.

TL;DR

  • Security defaults: DrnDefaults enforces MFA, nonce-based script CSP, and HSTS outside Development.
  • Startup: DrnProgramBase provides hooks for registration, middleware, and validation.
  • Routing: Typed controller endpoint accessors bind to mapped routes; page accessors generate Razor paths.
  • Local infrastructure: DRN.Framework.Testing provides opt-in Postgres provisioning.
  • Frontend: Razor TagHelpers handle Vite manifests, CSP nonces, and HTMX CSRF headers.

Table of Contents


QuickStart: Beginner

Use a .NET 10 web project with a DRN.Framework.Hosting package reference. Inherit from DrnProgramBase<TProgram> and register application services. Configure Environment, NexusAppSettings:AppId, NexusAppSettings:AppInstanceId, and NLog before calling RunAsync; see Configuration.

using DRN.Framework.Hosting.DrnProgram;
using DRN.Framework.Hosting.HealthCheck;
using DRN.Framework.Utils.DependencyInjection;
using DRN.Framework.Utils.Logging;
using DRN.Framework.Utils.Settings;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;

namespace Sample.Hosted;

public class Program : DrnProgramBase<Program>, IDrnProgram
{
    public static async Task Main(string[] args) => await RunAsync(args);

    protected override Task AddServicesAsync(
        WebApplicationBuilder builder,
        IAppSettings appSettings,
        IScopedLog scopedLog)
    {
        builder.Services.AddServicesWithAttributes();
        return Task.CompletedTask;
    }
}

// WeatherForecastControllerBase supplies [AllowAnonymous] and [HttpGet].
[Route("[controller]")]
public class WeatherForecastController : WeatherForecastControllerBase;

QuickStart: Advanced

Use DRN.Framework.Testing for integration tests that create the application pipeline and its configured database dependencies. Place tests using DrnTestContext in an integration test project.

public class WeatherForecastTests
{
    [Theory, DataInline]
    public async Task WeatherForecast_Should_Return_Data(DrnTestContext context)
    {
        var client = await context.ApplicationContext.CreateClientAsync<Program>();
        var response = await client.GetAsync("WeatherForecast");

        response.StatusCode.Should().Be(HttpStatusCode.OK);
        var data = await response.Content.ReadFromJsonAsync<IEnumerable<WeatherForecast>>();
        data.Should().NotBeEmpty();
    }
}

ApplicationContext automatically uses the active xUnit v3 output helper when each application is created, but only while a debugger is attached to preserve the log privacy gate. Do not request ITestOutputHelper as a [DataInline] theory parameter for application logging: AutoFixture supplies an interface substitute, not xUnit's runner-owned helper.

Lifecycle & Execution Flow

Use configuration hooks for services and options, pipeline hooks for middleware, and DrnProgramActions for startup integration. The diagram shows startup order; the pipeline table lists the complete request sequence.

flowchart TD
    Start(["RunAsync: settings and bootstrap logging"])
    Start --> Time["Validate configured ID generation time"]
    Time --> Builder["ConfigureSwaggerOptions; create builder and load settings"]
    Builder --> Configure["ConfigureApplicationBuilder; AddServicesAsync"]
    Configure --> Callback["Optional configureBuilder callback"]
    Callback --> Created["ApplicationBuilderCreatedAsync"]
    Created --> Build["Build; ConfigureApplication"]
    Build --> Built["ApplicationBuiltAsync"]
    Built --> Validate["ValidateEndpoints; ValidateServicesAsync"]
    Validate --> Validated["ApplicationValidatedAsync"]
    Validated --> Temporary{"Temporary application?"}
    Temporary -->|"Yes"| Return(["Return without starting"])
    Temporary -->|"No"| Run["StartAsync; WaitForShutdownAsync"]
    Run --> Dispose(["Dispose application"])

    %% Phase and decision styles
    classDef step fill:#FFFFFF,stroke:#37474F,stroke-width:2px,color:#263238
    classDef decision fill:#FFE0B2,stroke:#E65100,stroke-width:3px,color:#263238
    class Start,Time,Builder,Configure,Callback,Created,Build,Built,Validate,Validated,Return,Run,Dispose step
    class Temporary decision

The four-argument CreateApplicationAsync(args, appSettings, scopeLog, configureBuilder) overload invokes its builder callback after AddServicesAsync and before ApplicationBuilderCreatedAsync. The three-argument overload omits that callback. Both return a configured application without starting it; RunAsync owns startup and shutdown.

Host creation validates Source-Known generation time before program/actions constructors and hooks. Read-only hosts, temporary applications, and SkipValidation do not bypass this check. The default minimum is 2026-09-09T00:00:00Z; SourceKnownIdSettings:MinimumUtc can replace it with an earlier or later UTC value.

Optional DefaultEpoch changes the origin used by generation, decoding, and date filters; supplying it requires an explicit MinimumUtc. For example:

{
  "SourceKnownIdSettings": {
    "DefaultEpoch": "2026-01-01T00:00:00Z",
    "MinimumUtc": "2026-09-09T00:00:00Z"
  }
}

Configure before startup or first ID/epoch use, including historical reads. Both values then freeze, even if the generation-time check fails. Keep the epoch unchanged across every service and restart using the dataset: IDs do not store their origin. See the Utils time contract for input formats, rounding, and historical reads.

Define at most one concrete DrnProgramActions subclass in the application assembly, with a public parameterless constructor. Its three callbacks run at the points shown above. See local development for an example.

Temporary applications build and configure the request pipeline, then enter the service-validation phase, which honors DrnDevelopmentSettings:SkipValidation. They skip endpoint validation and endpoint-accessor population, and return before the host calls StartAsync.

DrnProgramBase Deep Dive

Override these hooks to customize startup and request processing. Preserve base calls when extending defaults; replacing a hook makes the application responsible for the behavior it removes.

1. Configuration Hooks (Builder Phase)

These hooks register services or customize configuration. Options callbacks run when their options are created. Security-header callbacks run when the policy provider builds its policies.

Category Method Purpose
Builder ConfigureApplicationBuilder Register hosting services and callbacks before AddServicesAsync. Call base to retain DRN wiring.
Logging ConfigureLoggingBuilder Clear default providers, apply logging configuration, and register NLog when its section exists. See NLog for bootstrap requirements.
WebHost ConfigureWebHostBuilder Configure Kestrel options (suppresses Server header, applies optional Kestrel section, registers static web assets).
OpenAPI ConfigureSwaggerOptions Customize Swagger UI title, version, and visibility settings.
MVC ConfigureMvcBuilder Add ApplicationParts, custom formatters, or MVC/Razor options. See Razor Development.
MVC ConfigureMvcOptions Add global filters, conventions, or customize model binding.
Auth ConfigureAuthorizationOptions Define policies; both default and fallback policies require MFA.
Security ConfigureDefaultSecurityHeaders Define global headers (HSTS, CSP, FrameOptions).
Security ConfigureDefaultCsp Customize CSP directives (Script, Image, Style sources).
Security ConfigureDefaultCspBase Customize shared CSP directives such as base URI, form actions, and frame ancestors.
Security ConfigureSecurityHeaderPolicyBuilder Advanced conditional security policies (e.g., per-route CSP).
Cookies ConfigureCookiePolicy Set GDPR consent logic and security attributes for all cookies.
Cookies ConfigureCookieTempDataProvider Configure TempData cookie settings (HttpOnly, IsEssential).
Identity ConfigureIdentityRenewal(IServiceCollection, IAppSettings); ConfigureSecurityStampValidatorOptions(SecurityStampValidatorOptions, IAppSettings, AuthenticationClaimConfig) Register/customize Identity cookie renewal while retaining shared claim configuration.
Infras. ConfigureStaticFileOptions Customize static-file serving and public cache headers.
Infras. ConfigureForwardedHeadersOptions Configure proxy/load-balancer header forwarding.
Infras. ConfigureRequestLocalizationOptions Configure culture providers and supported cultures.
Infras. ConfigureHostFilteringOptions Configure allowed hosts for host header validation.
Infras. ConfigureResponseCachingOptions Set cache limits; defaults to a 16 MiB maximum body size and case-insensitive paths.
Global AddServicesAsync Required application service registration hook.

Razor Development

DRN uses Razor SDK build-time and publish-time compilation. For local .cshtml iteration, use IDE Hot Reload or dotnet watch instead of Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation; runtime compilation is obsolete in .NET 10 and disables Hot Reload.

References:

2. Pipeline Hooks (Application Phase)

With DrnDefaults, ConfigureApplication installs the following sequence. Rows without a hook name are framework middleware between hooks.

Order Hook or middleware Default behavior
1 ConfigureApplicationPipelineStart Forwarded headers, host filtering, cookie policy, security headers, and HSTS outside Development.
2 ConfigureApplicationPreScopeStart Response caching followed by static-file serving, including prebuilt Brotli assets.
3 HttpScopeMiddleware Request scope, logging, buffering, exception handling, and response controls.
4 ConfigureApplicationPostScopeStart Empty hook for middleware needing the request scope before routing.
5 UseRouting Select the endpoint and its metadata.
6 PreAuthRateLimitingMiddleware Pre-auth rules when rate limiting is enabled.
7 ConfigureApplicationPreAuthentication Request localization when enabled.
8 UseAuthentication, then ScopedUserMiddleware Authenticate and populate the scoped user.
9 UseRateLimiter Post-auth rules and named policies when rate limiting is enabled.
10 ConfigureApplicationPostAuthentication MFA exemption middleware, then MFA redirection middleware, each when configured.
11 UseAuthorization Enforce endpoint authorization.
12 ConfigureApplicationPostAuthorization Map Swagger and add its UI when enabled.
13 MapApplicationEndpoints Map controllers and Razor Pages. Override to add other endpoints, such as hubs.

Static files served at step 2 bypass the request scope, authentication, authorization, and rate limiting. Serve only public assets through this stage.

3. Verification Hooks

Hook Purpose
ValidateEndpoints Binds and validates controller endpoint accessors against mapped routes and records mapped page endpoints.
ValidateServicesAsync Scans the container for [Attribute] based registrations and ensures they are resolvable at startup via ValidateServicesAddedByAttributesAsync.

For MFA hooks and examples, see MFA.

4. Properties

Property Default Purpose
AppBuilderType DrnDefaults DrnDefaults applies the complete DRN hosting and security pipeline. Empty, Slim, and Default are advanced opt-out modes; the application must configure its required services, middleware, and endpoints.
DrnProgramSwaggerOptions (Object) Toggles Swagger generation. Defaults to IsDevelopmentEnvironment.
NLogOptions (Object) Controls NLog bootstrapping (e.g., replace logger factory).

DrnProgramBase also automatically registers the public IEndpointAccessor dependency-injection contract as a singleton. Consumers can inject IEndpointAccessor to query the endpoint collections (Endpoints, ApiEndpoints, PageEndpoints, and PageEndpointByPaths) populated by ValidateEndpoints before service validation (ValidateServicesAsync) runs.

Swagger Access Outside Development

Override ConfigureSwaggerOptions, call base, then set AddSwagger = true and AuthorizationPolicy to an application-owned named policy. Register that policy with RequireAuthenticatedUser() and the appropriate administrative role. The default MFA enforcement also applies.

AuthorizationPolicy protects Swagger UI, its assets, and JSON/YAML documents, including a document route outside the UI prefix. A null policy preserves existing authorization behavior. Empty or whitespace policy names are rejected. The framework still enables Swagger only in Development by default.

Configuration

Set NexusAppSettings:AppId and NexusAppSettings:AppInstanceId explicitly in every environment, including when either value is zero. AppId accepts 0 through 127 and must match the application's entity partition. AppInstanceId accepts 0 through 63; assign distinct values to concurrent instances generating IDs for that application. Staging and Production require private DrnAppFeatures:SeedKey and Nexus keys. See Utils configuration for key requirements.

Layering

Later sources override earlier ones. Keep local connection strings in User Secrets rather than committed settings files.

  1. appsettings.json
  2. appsettings.{Environment}.json
  3. User Secrets when the application assembly can be loaded
  4. Environment Variables (ASPNETCORE_, DOTNET_, then unprefixed)
  5. Mounted Directories (default: /appconfig)
  6. Command Line Arguments

Environment is required and must be Development, Staging, or Production. Bootstrap resolves it from appsettings.json, environment variables, mounted settings, or command-line arguments before loading environment-specific settings or User Secrets. Missing, NotDefined, or unknown values fail startup with ConfigurationException.

Host Filtering

AllowedHosts must be configured outside Development and cannot be *. Development may fall back to * for local convenience; production and staging should use explicit host names such as example.com;api.example.com.

Reference Configurations

NLog (Logging)

Minimal NLog configuration for console output. Add and route a Graylog target if your deployment uses Graylog. Logging providers are cleared and NLog is added during host construction only when the NLog configuration section exists, while RunAsync still requires the section for bootstrap logging.

{
  "NLog": {
    "throwConfigExceptions": true,
    "targets": {
      "async": true,
      "console": {
        "type": "Console",
        "layout": "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}"
      }
    },
    "rules": [
      { "logger": "*", "minLevel": "Info", "writeTo": "console" }
    ]
  }
}
Kestrel (Server)
{
  "Kestrel": {
    "EndpointDefaults": { "Protocols": "Http1" },
    "Endpoints": {
      "All": { "Url": "http://*:5988" }
    }
  }
}
Forwarded Headers (Reverse Proxy & Gateway)

ConfigureForwardedHeadersOptions configures ASP.NET Core ForwardedHeadersOptions for reverse proxy, load balancer, and gateway header forwarding.

When a trusted proxy strips a deployment prefix, forward it with X-Forwarded-Prefix to populate Request.PathBase. Generate URLs from processed request properties, as Swagger does, rather than raw forwarding headers.

Application URLs

Keep routes independent of deployment prefixes. Under /gateway, the route /Api/Items becomes /gateway/Api/Items.

Context Convention
Razor Pages navigation Prefer asp-page and RedirectToPage.
Razor URLs Use ~/... in href, src, action, formaction, and HTMX request attributes. Import @addTagHelper *, DRN.Framework.Hosting for ApplicationUrlTagHelper.
C# URL generation Use MVC page/action routing or request-aware LinkGenerator. Use Url.Content("~/...") for application-relative paths.
Endpoint accessors Import DRN.Framework.Hosting.Extensions and use Url.Endpoint(Get.Endpoint.QA.Tag.GetAsync, new { id }).
Sample navigation Use ForPage(pageName, title) for pages and ForUrl(href, title) for URLs. Shared views render asp-page or href accordingly.
Configured destinations Use Request.ApplicationUrl(path) from DRN.Framework.Hosting.Extensions for application-owned /... or ~/... paths, such as MFA destinations. Queries and fragments are retained; other URLs are unchanged.
Sample browser code Use DRN.App.url('~/Api/Items'). It resolves only ~/ using the layout's drn-app-base metadata.

Validate return URLs with Url.IsLocalUrl and redirect unchanged. Never pass resolved URLs through ApplicationUrl. Deployment prefixes and route segments are separate, even when both are /api. Literal /... HTML and JavaScript URLs remain origin-root-relative.

Configure MFA destinations without the deployment prefix. Redirects add PathBase and retain the public return path and query.

Pass parentContext to IPageUtils.RenderPageAsync to retain the request's PathBase and CSP nonce. Standard _ViewStart files and layouts follow normal Razor rendering. Page links use endpoint routing, including when the original request has no matching endpoint. Each render owns a separate DI scope and awaits its disposal on success or failure. The parent request scope remains owned by its caller.

Url.Endpoint requires metadata populated by DRN startup validation. It uses MVC's effective action name and destination area without modifying supplied route values. Missing or ambiguous metadata and failed generation throw InvalidOperationException. Existing ApiEndpoint.Path(...) methods remain available. Keep static Get accessors request-independent.

Proxy Trust Configuration

DRN trusts loopback and RFC 1918 networks (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) with ForwardLimit = 2. This supports private-network proxies. Without trusted forwarding, requests can share the proxy IP and its rate-limit quota.

  • Remove private-network defaults with TrustPrivateNetworks: false:

    {
      "ForwardedHeaders": {
        "TrustPrivateNetworks": false
      }
    }
    

    With no other entries configured, this retains loopback (127.0.0.0/8, ::1/128).

  • Configure networks and proxies:

    {
      "ForwardedHeaders": {
        "ForwardLimit": 2,
        "KnownIPNetworks": [
          "10.244.0.0/16",
          { "BaseAddress": "192.168.1.0", "PrefixLength": 24 }
        ],
        "KnownProxies": [ "10.0.0.100" ]
      }
    }
    

    A nonempty KnownIPNetworks list replaces the network defaults. KnownProxies adds individual proxies and does not clear existing proxies or networks. For an exact allowlist, override the options callback and clear both collections before adding trusted entries.

Security Features

The defaults in this section apply to AppBuilderType.DrnDefaults when the base lifecycle hooks are preserved. Other builder modes require the application to configure its complete security and middleware pipeline.

MFA

MFA is required by default, including endpoints with role or named policies.

Use [AllowAnonymous] for public endpoints such as login. Authenticated endpoints have two separate MFA exemption paths:

Path Requirement
AuthPolicy.MfaExempt Authentication without MFA. Add a scheme restriction if required.
ConfigureMFAExemption An eligible scheme must also be selected by the endpoint policy or default authentication scheme.

For restricted enrollment or challenge access, use the Identity policies below. They add scheme and credential-state checks.

Sample and Nexus register Identity.BearerAndApplication as their default through AddIdentityApiEndpoints. It tries bearer authentication first, then application cookies when no bearer token is present. An invalid bearer token does not fall back to cookies. See the ASP.NET Core implementation.

Configuration

Configure MFA behavior by overriding these hooks in your DrnProgramBase implementation:

// Page accessors from Sample.Hosted.
protected override MfaRedirectionConfig ConfigureMFARedirection()
    => new(
        mfaSetupUrl: Get.Page.User.Management.EnableAuthenticator,
        mfaLoginUrl: Get.Page.User.LoginWith2Fa,
        loginUrl: Get.Page.User.Login,
        logoutUrl: Get.Page.User.Logout,
        appPages: Get.Page.All
    );

// Optional; ordinary Identity applications need no claim override.
protected override AuthenticationClaimConfig ConfigureAuthenticationClaims()
    => AuthenticationClaimConfig.Default;

// Eligible schemes must also be selected for authentication.
protected override MfaExemptionConfig ConfigureMFAExemption()
    => new() { ExemptAuthSchemes = ["ApiKey", "Certificate"] };

ConfigureAuthenticationClaims defaults to Identity claim types and amr=mfa. See Renewal and assurance for custom mappings and their migration requirements.

For example, register ApiKey, add it to the exemption list, and select it in an API policy that requires an API scope. Listing ApiKey alone does not let it access default endpoints using Identity.BearerAndApplication. Programmatic MFA checks without an HTTP policy context require completed MFA.

Shared MFA authorization does not require ASP.NET Core Identity or its database. External providers need trusted authentication handlers and claim mapping. Local browser redirection is opt-in; return null from ConfigureMFARedirection to omit it.

Absent or incomplete authentication configuration

Register an effective authentication, challenge, and forbid scheme through AddAuthentication or endpoint policies. With multiple schemes, select them explicitly. A missing challenge/forbid scheme causes a server configuration error (HTTP 500), not an authentication response. An app can start and serve [AllowAnonymous] endpoints without schemes.

References: MVC registration, scheme selection, authentication errors.

Renewal and assurance

Register the Identity sign-in integration and MFA policies through the standard builder:

services.AddIdentityApiEndpoints<AppUser>()
    .AddSignInManager<DrnSignInManager<AppUser>>();
services.AddDrnIdentityMfaPolicies();

AddDrnIdentityMfaPolicies is in DRN.Framework.Hosting.Identity. IdentityMfaPolicy.Enrollment uses the Identity cookie/bearer composite. BrowserEnrollment and Challenge use application cookies only. Pass identityApiScheme to select an equivalent application-owned composite.

IdentityManagementControllerBase uses API controller behavior: authentication failures return 401 or 403, and invalid request models return validation Problem Details before the action runs. Derived controllers must use attribute routes.

Derive custom sign-in managers from DrnSignInManager<TUser> to retain DRN's renewal behavior. When customizing ConfigureSecurityStampValidatorOptions, set callbacks before calling base. Omit ConfigureIdentityRenewal wiring only when Identity cookie renewal is unused.

Refresh preserves the original authentication age; it does not count as fresh MFA. MfaPrincipal.IsRecent and IsPhishingResistant are opt-in checks requiring supporting evidence from the authentication provider.

For a provider with custom claim names:

protected override AuthenticationClaimConfig ConfigureAuthenticationClaims() => new()
{
    Subject = new("sub"), Name = new("preferred_username"), Email = new("email"),
    Roles = new("roles"), Mfa = new("acr", "urn:example:mfa")
};

Replace the example MFA value with one guaranteed by your provider. Custom subject, name, email, role, and MFA mappings also replace their corresponding aliases. Configure the validating handler to issue these claims and native name/role mappings. This hook does not implement provider login or refresh.

Use this hook rather than changing IdentityOptions.ClaimsIdentity separately. Changing subject types may require reauthentication. See the Utils claim contract.

Audit events

With global MFA enabled, these Information-level events support log filters and alerts.

Event name ID Meaning
MfaAuthorizationChallenge 7401 Authentication challenge.
MfaAuthorizationForbid 7402 Access denied.
MfaAuthorizationExemption 7403 Effective policy or scheme exemption.

HostingLogEvents in DRN.Framework.Hosting.Logging exposes these public EventId fields. See Logging conventions for consumer catalogs and filtering.

MFA decisions use the shared scope-event API:

scopedLog.WithEvent(new ScopeEvent(
    HostingLogEvents.MfaAuthorizationForbid,
    Outcome: "forbid",
    Reason: "mfa_required"));

ScopeEvent comes from DRN.Framework.Utils.Logging. Filter audit events by logger category and event ID; use scoped logs for request diagnostics. Request logs may contain identifiers, so configure retention accordingly.

Identity Revocation Contract

Under the default Identity handlers, credential revocation depends on the credential type:

Credential After a persisted security-stamp change
Refresh token The next /Refresh request rejects it; expiration is checked independently.
Application cookie Rejected on the next request eligible for stamp validation: elapsed time since ticket issuance must be greater than SecurityStampValidatorOptions.ValidationInterval. This is request-driven, not a background deadline.
Opaque bearer access token Remains usable until its own expiration, unless the application adds rejection checks. Stamp rotation alone does not invalidate it.

Cookie timing follows SecurityStampValidator; access-token timing follows BearerTokenHandler. Configured handlers, stores, validation intervals and token lifetimes can change these bounds.

UpdateSecurityStampAsync, factor enable/disable, authenticator-key reset, and password reset rotate the stamp. Recovery-code generation and redemption do not. To revoke sessions after recovery, rotate the stamp and account for outstanding access-token lifetime. See UserManager.

Identity API MFA Setup Flow

With global MFA enabled, password login without an enrolled factor issues a five-minute MfaSetupRequired credential:

  • Cookie requests: Return an empty HTTP 200 response and set a non-persistent cookie with refresh disabled.
  • Bearer requests: Return an HTTP 200 AccessTokenResponse containing the setup access token, ExpiresIn = 300, and an empty RefreshToken.

Use the credential with IdentityManagementControllerBase.TwoFactorAuth to retrieve a shared key and enroll with a valid code. Discard it after enrollment. Call Login again with the password and an authenticator or recovery code to obtain completed MFA.

A setup credential does not grant normal MFA-protected access.

With global MFA disabled, users without a factor can enroll using an ordinary login credential. After enrollment, factor management requires completed MFA; denied operations return HTTP 403. Other management endpoints retain normal MFA requirements. Register the Identity policies as shown in Renewal and assurance.

Remaining MFA work

Fresh step-up/replay protection, recovery workflows, passkeys, provider-specific OIDC integrations, and factor/recovery audit events are not complete. See the implementation roadmap before relying on these capabilities.

Disabling global MFA

In your existing DrnProgramBase subclass, replace both default policies with an authenticated-user policy. Explicit MFA policies still apply. Remove any redirection or exemption overrides, or return null from them.

protected override void ConfigureAuthorizationOptions(AuthorizationOptions options)
{
    base.ConfigureAuthorizationOptions(options);
    var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
    options.DefaultPolicy = policy;
    options.FallbackPolicy = policy;
}

Browser security

DRN generates a request-specific cryptographic nonce.

  • Baseline: default-src 'none'; script elements require the request nonce. Other directives permit same-origin styles, images, fonts, connections, media, manifests, and workers, plus inline style attributes, data: images and fonts, and blob: workers.
  • Automatic Protection: Inline scripts and inline style elements without a matching nonce are blocked. Inline style attributes remain allowed by the default policy.
  • Usage: Activate and use the NonceTagHelper below to add the request nonce.

Standard security headers are injected into responses:

  • HSTS: Strict-Transport-Security (2 years, includes subdomains) outside Development.
  • FrameOptions: DENY (prevents clickjacking).
  • ContentTypeOptions: nosniff.
  • ReferrerPolicy: strict-origin-when-cross-origin.
  • Cross-Origin: COOP same-origin, COEP credentialless, and CORP same-site.
  • PermissionsPolicy: Secure default directives with fullscreen limited to self.

Cookies use SameSite=Strict. Secure is Always outside Development and SameAsRequest in Development. Antiforgery and TempData cookies are HttpOnly; the global policy does not force it for client-readable cookies.

CheckConsentNeeded = true withholds nonessential response cookies until consent is granted. ConsentContext exposes the current request's preferences. Applications decide which scripts need consent and which cookies are essential.

For example, load an application-owned analytics entry only after analytics consent:

@using DRN.Framework.Hosting.Consent

@if (ConsentContext.ConsentCookie.Values.AnalyticsConsent == true)
{
    <script src="buildwww/app/js/analytics.js"
            crossorigin="anonymous"></script>
}

Route-specific security headers

Leading and trailing slashes are removed from the configured Swagger UI prefix before both middleware routing and CSP selection; /docs/ becomes docs.

When Swagger is enabled, its UI RoutePrefix must be nonempty after trimming slashes, for example swagger, docs/swagger, or api-docs. Validation runs after ConfigureSwaggerUIOptionsAction. A null, empty, or slash-only prefix fails startup with ConfigurationException: a root mount would apply Swagger CSP across the application.

The complete configured subtree is reserved for CspFor.CspPolicySwagger, including application endpoints beneath it. Matching is case-insensitive and respects path segment boundaries. Keep ordinary application pages outside that subtree. Disabling Swagger leaves application policies unchanged.

The Swagger policy allows scripts from 'self' and styles from 'self' 'unsafe-inline' to support inline SVG styles without changing the generated document or its caching. It replaces the shared style-src directive. Self/inline endpoint policies retain their nonce-based styles. Replace CspFor.CspPolicySwagger through builder.AddPolicy after calling base to customize Swagger independently; selecting that name through CspPolicyName does not opt unrelated endpoints into it.

Customize security headers for specific routes by overriding ConfigureSecurityHeaderPolicyBuilder. This example replaces the base policy selector: routes outside /legacy receive the default policy, including Swagger routes. Preserve the base selection rules too if the application uses Swagger or endpoint-selected CSP policies.

protected override void ConfigureSecurityHeaderPolicyBuilder(
    SecurityHeaderPolicyBuilder builder,
    IServiceProvider serviceProvider,
    IAppSettings appSettings)
{
    base.ConfigureSecurityHeaderPolicyBuilder(builder, serviceProvider, appSettings);
    
    // Allow legacy inline scripts on /legacy routes.
    var legacyPolicy = new HeaderPolicyCollection();
    ConfigureDefaultSecurityHeaders(legacyPolicy, serviceProvider, appSettings);
    legacyPolicy.Remove("Content-Security-Policy");
    legacyPolicy.AddContentSecurityPolicy(csp =>
    {
        ConfigureDefaultCspBase(csp);
        csp.AddFrameAncestors().Self();
        csp.AddScriptSrc().Self().UnsafeInline(); // Only for selected legacy routes
    });
    builder.AddPolicy("legacy-inline-csp", legacyPolicy);
    builder.SetPolicySelector(selector =>
        selector.HttpContext.Request.Path.StartsWithSegments("/legacy")
            ? selector.ConfiguredPolicies["legacy-inline-csp"]
            : selector.DefaultPolicy);
}

Rate Limiting

DRN Hosting adds two composable limiter phases:

  • Pre-auth runs after routing and before authentication. It evaluates singleton rules only and uses a coarse IP default to reject obvious abuse before auth and MFA work. Add a custom singleton rule for trusted-header partitioning behind a correctly configured edge proxy.
  • Post-auth runs after ScopedUserMiddleware. It can use singleton and scoped rules, including user, tenant, account, claim, or endpoint partitions.

Defaults are token buckets: 2,500 tokens/minute per pre-auth IP partition and 250 tokens/minute per post-auth user partition. Post-auth uses the authenticated subject and authentication type; requests without a usable authenticated subject fall back to IP. Rejections return 429 Too Many Requests; Retry-After is included only when the rejecting limiter supplies retry metadata.

DRN's built-in limiter state is process-local. In horizontally scaled production deployments, enforce coarse limits at the edge (WAF/CDN/API gateway/load balancer) or add a distributed/custom limiter for quotas that must hold across every application instance.

Endpoint metadata behavior:

  • [DisableRateLimiting] bypasses DRN pre-auth and post-auth limiting, plus ASP.NET Core post-auth policies.
  • [EnableRateLimiting("policy-name")] selects ASP.NET Core named post-auth policies. DRN pre-auth remains global; DRN rules with matching PolicyName compose with the named policy.
  • Static files served before routing are naturally outside the limiter path.

When many users share an edge IP, raise the pre-auth quota or use a trusted-header rule. Use scoped post-auth rules for account or tenant quotas, as shown below.

Settings Quick Reference

Configure defaults under DrnAppFeatures:DrnRateLimit. Read them through IAppSettings.Features.RateLimit. Changes require restart. Shared bucket values must be positive; phase overrides can be 0 to inherit them.

Setting group Default Used by Meaning
Disabled false Both phases Disables DRN pre-auth and post-auth rate limiting.
PartitionLogMode KeyedHash Both phases Controls rejected IP and partition logging. See Telemetry for hash format and privacy limits.
TokenLimit, ReplenishmentSeconds, TokensPerPeriod 250, 60, 250 Shared fallback Base token bucket values for both phases.
PreAuthTokenLimit, PreAuthReplenishmentSeconds, PreAuthTokensPerPeriod 2500, 60, 2500 Pre-auth Coarse IP limits before authentication. 0 inherits the shared value.
PostAuthTokenLimit, PostAuthReplenishmentSeconds, PostAuthTokensPerPeriod 0, 0, 0 Post-auth Authenticated user or anonymous IP limits after ScopedUserMiddleware. 0 inherits the shared value.
Rule Extension Points

Add rules by deriving from SingletonRateLimitRule or ScopedRateLimitRule; the base classes include attribute-based DI registration. Direct interface implementations must opt into multi-registration with [Singleton<ISingletonRateLimitRule>(tryAdd: false)] or [Scoped<IScopedRateLimitRule>(tryAdd: false)].

Rules run by ascending Order; framework defaults run last. Matching rules compose through .NET's chained limiter, so tenant + user + IP policies can all apply to one request. ScopedRateLimitRule is post-auth only.

Return value Effect
null Rule does not apply.
RateLimitRuleResult.TokenBucket(key, ...) Applies a token bucket to this partition.
RateLimitRuleResult.AllowRequest("partition-key") Skips later rules in this phase. Earlier limits and native policies still apply.
RateLimitRuleResult.DenyRequest("partition-key") Rejects immediately with 429.
Any result with stopRemainingRules: true Applies this result and skips later rules.

Partition helpers include TokenBucket, FixedWindow, SlidingWindow, ConcurrencyLimiter, and CustomPartition. RateLimitRuleResult.Action is Limit, Allow, or Deny; StopRemainingRules only controls whether later rules compose after this result.

Set PolicyName to match [EnableRateLimiting("policy-name")], or leave it null for a global rule. Empty names are invalid. Native policies registered through AddRateLimiter run alongside DRN rules. A rejecting DRN rule receives OnRejectedAsync; native policy rejections use the ASP.NET Core callback.

Use ShortCircuitOnMatch and lower Order for allow/deny rules that must bypass quota checks. Rules with the same Order evaluate short-circuit rules first; if a short-circuit rule returns null, later rules still evaluate.

Partition option factories are cached by .NET per partition key. Do not capture HttpContext or scoped services inside factory lambdas; pass only immutable values.

Dynamic tenant plans belong in rules, not global settings. Rule evaluation is synchronous, so do not perform database, Redis, or HybridCache I/O inside EvaluatePreAuth / EvaluatePostAuth. Load plan data earlier in the request or maintain an in-memory snapshot refreshed in the background. HybridCache and IDistributedCache can share policy data, but they are not hard distributed counters by themselves.

// Sample.Hosted/Helpers/RateLimitFor.cs
public class RateLimitFor
{
    public string? AccountPartition => Get.Claim.Account.Id == null ? null : $"account:{Get.Claim.Account.Id:N}";
    public string? TenantPartition => Get.Claim.Tenant.Id == null ? null : $"tenant:{Get.Claim.Tenant.Id:N}";
}

public class AccountRateLimitRule(DrnAppFeatures features) : ScopedRateLimitRule
{
    public override RateLimitRuleResult? EvaluatePostAuth(HttpContext context)
    {
        var partitionKey = Get.RateLimit.AccountPartition;
        if (partitionKey == null)
            return null;

        var tokenLimit = features.RateLimit.TokenLimit;
        var period = TimeSpan.FromSeconds(features.RateLimit.ReplenishmentSeconds);
        var tokensPerPeriod = features.RateLimit.TokensPerPeriod;
        return RateLimitRuleResult.TokenBucket(partitionKey, _ => new TokenBucketRateLimiterOptions
        {
            TokenLimit = tokenLimit,
            ReplenishmentPeriod = period,
            TokensPerPeriod = tokensPerPeriod,
            QueueLimit = 0,
            AutoReplenishment = true
        });
    }
}
Telemetry

DRN emits metrics through the DRN.Framework.Hosting.RateLimiting meter:

Metric DRN coverage
drn.rate_limiting.requests Pre-auth lease acquisition attempts
drn.rate_limiting.rejections Pre-auth and post-auth rejections
drn.rate_limiting.active_request_leases Active pre-auth leases
drn.rate_limiting.request_lease.duration Pre-auth lease duration in seconds

All instruments use drn.rate_limiting.phase, aspnetcore.rate_limiting.policy, aspnetcore.rate_limiting.result, and drn.rate_limiting.action. The action is limit, allow, deny, or unknown. drn.rate_limiting.rule is added when a DRN rule is known; native policy rejections have no DRN rule tag. ASP.NET Core supplies post-auth request and lease metrics.

Subscribe to this meter through the host's metrics exporter to derive requests per second from counter deltas. A rate averaged over a collection interval is not an exact count for the preceding second. drn.rate_limiting.requests counts pre-auth acquisition outcomes, excluding endpoints that bypass limiting; it is not total application traffic. Do not add pre-auth and post-auth counts together, since a request can pass through both phases.

Use actual drn.rate_limiting.rejections with action limit to identify limiter rejections. Treat deny as an explicit rule decision and unknown as unattributed, not proof of token exhaustion. Rejection logs expose the same action as PreAuthRateLimitRejectedAction or PostAuthRateLimitRejectedAction. A rejection alone does not prove abusive traffic. Keep phase, rule, policy, and application instance distinct when investigating; use the redacted partition in logs for bucket correlation rather than adding partition identifiers as metric tags.

Do not compare one-second traffic to TokensPerPeriod / ReplenishmentSeconds to declare a limit exceeded. Token buckets allow bursts up to their available capacity and replenish on their configured schedule. Fleet-wide or cross-partition traffic is not one bucket's usage. Limiter leases remain the source of truth, including custom rules and algorithms; use Retry-After only when the rejecting lease supplies it.

By default, rate-limit-specific IP and partition fields are written as deterministic keyed hashes with a blake3-keyed: prefix. This supports correlation but does not anonymize the complete request log; standard request and user fields may still contain raw identifiers. Treat logs as sensitive, and enable PlainText only for controlled development or a dedicated encrypted audit sink.

Overriding Defaults

Override CreatePreAuthRateLimiter or ConfigurePostAuthRateLimiterOptions in DrnProgramBase to change global algorithms, add named policies, or preserve custom RateLimiterOptions callbacks:

protected override void ConfigurePostAuthRateLimiterOptions(
    RateLimiterOptions options,
    IServiceProvider serviceProvider,
    IAppSettings appSettings)
{
    base.ConfigurePostAuthRateLimiterOptions(options, serviceProvider, appSettings);
    options.AddTokenBucketLimiter("strict", opt =>
    {
        opt.TokenLimit = 10;
        opt.ReplenishmentPeriod = TimeSpan.FromSeconds(60);
        opt.TokensPerPeriod = 10;
        opt.QueueLimit = 0;
    });
}
References

Endpoint Management

DRN provides compile-time-typed accessor members for controller endpoints and Razor Page paths. Controller endpoint accessors are bound to mapped routes and validated at startup. Razor Page accessors are convention-generated path strings; keep them synchronized with page routes.

1. Define Accessors

Create application-owned endpoint and page collections:

public sealed class AppEndpoints : EndpointCollectionBase<Program>
{
    public UserEndpoints User { get; } = new();
}

public sealed class UserEndpoints()
    : ControllerForBase<UserController>("/Api/User/[controller]")
{
    // Property names match controller action method names.
    public ApiEndpoint Login { get; private set; } = null!;
    public ApiEndpoint Profile { get; private set; } = null!;
}

public sealed class AppPages : PageCollectionBase<AppPages>
{
    public UserPages User { get; } = new();
}

public sealed class UserPages : PageForBase
{
    protected override string[] PathSegments { get; } = ["User"];
    public string Login { get; init; } = string.Empty;
}

public static class Get
{
    public static AppEndpoints Endpoint { get; } =
        (AppEndpoints)EndpointCollectionBase<Program>.EndpointCollection!;

    public static AppPages Page { get; } =
        PageCollectionBase<AppPages>.PageCollection;
}

2. Usage in Code

Use the typed accessor members with IDE completion:

// Get the typed endpoint object
ApiEndpoint endpoint = Get.Endpoint.User.Login;

// Return the mapped controller route.
string url = endpoint.Path();

// For an action route containing {id:guid}
Guid userId = Guid.NewGuid();
string profileUrl = Get.Endpoint.User.Profile.Path(userId);
<a asp-page="@Get.Page.User.Login">Log in</a>

Razor TagHelpers

Activate the framework TagHelpers in Pages/_ViewImports.cshtml:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, DRN.Framework.Hosting

Without the DRN directive, Vite resolution, CSP nonces, HTMX CSRF headers, active-page marking, and visibility helpers do not run.

TagHelper Target Purpose
ViteScriptTagHelper <script src="buildwww/..."> or <script src="node_modules/..."> Resolves Vite manifest entries and adds subresource integrity (SRI).
ViteLinkTagHelper <link href="buildwww/..."> or <link href="node_modules/..."> Resolves Vite manifest entries for CSS assets, adds SRI.
NonceTagHelper <script>, <style>, <link>, <iframe> Automatically injects the request-specific CSP nonce.
CsrfTokenTagHelper hx-post, hx-put, hx-delete, hx-patch, or add-csrf-token Adds RequestVerificationToken to hx-headers. On matched elements, disable-csrf-token opts out.
AuthorizedOnlyTagHelper *[authorized-only] Renders the element only if the user is authenticated.
AnonymousOnlyTagHelper *[anonymous-only] Renders the element only if the user is not authenticated.
PolicyOnlyTagHelper *[policy-only="PolicyName"] Renders the element only when the current request user satisfies the named authorization policy. Accepts an optional policy-resource.
PageAnchorAspPageTagHelper <a asp-page="..."> Adds active fw-bold and aria-current="page" when the link matches the current page.
PageAnchorHrefTagHelper <a href="..."> On Razor Pages, adds active fw-bold and aria-current="page" when the resolved root-relative href path matches the public request path, including custom routes and deployment prefixes. Ignores queries and fragments. Absolute, protocol-relative, fragment-only, and relative links are not marked active. Use asp-page for page-identity matching.
ScriptDefaultsTagHelper <script> Modern defaults: defer for external scripts, type="module" for inline scripts. Opt-out via defer="false" or explicit type.

CsrfTokenTagHelper supplies tokens; it does not enable server-side validation for controller or minimal endpoints. Preserve Razor Pages' antiforgery conventions and configure appropriate validation for cookie-authenticated state-changing endpoints.

Set disable-nonce="true" to suppress nonce injection on an element. This does not change the Content Security Policy (CSP), so the browser can still block the element. Active-link helpers accept active-class to customize their CSS classes and mark-when-active="false" to disable class marking. A matching link still receives aria-current="page" when class marking is disabled.

Authorization Visibility

Use named policies for claim, role, or resource requirements instead of duplicating authorization rules in markup:

<a policy-only="ManageUsers" asp-page="/Admin/Users">Manage users</a>
<button policy-only="EditDocument" policy-resource="@Model.Document">Edit</button>
<nav authorized-only>Signed-in navigation</nav>
<a anonymous-only asp-page="/User/Login">Sign in</a>

policy-only checks a registered policy against the current user. Invalid policy names raise errors; denied elements are hidden. Supply policy-resource when the policy requires one. The helper does not sign users in or check the linked endpoint; ordinary named policies retain the default MFA requirement.

authorized-only checks ScopeContext.Authenticated; anonymous-only checks its inverse. Both are presence-only markers, so even "false" activates the filter. Write them without values, remove them to omit filtering, and use Razor conditionals for dynamic rendering. Both markers are removed from rendered HTML. If several visibility helpers apply, any one can suppress the element.

These markers do not require completed MFA. On anonymous or MFA-exempt pages, authorized-only can render for users with pending MFA or incomplete setup. Use policy-only for policy-specific visibility. All three helpers control HTML rendering only; enforce endpoint access through server authorization policies.

Vite Manifest Publish Support

Vite manifests under wwwroot/**/.vite/manifest.json are included automatically in publish output.

ViteManifest uses IWebHostEnvironment.WebRootPath, falling back to Path.Combine(environment.ContentRootPath, "wwwroot") when it is unset or whitespace.

When publishing with a custom web root, build targets do not automatically capture manifests outside wwwroot/**; applications must separately include manifests and referenced assets in publish items.

Before upgrading, add a hashing step to your Vite build. Stock Vite omits the hash field that DRN tag helpers use for subresource integrity. For every manifest entry, hash the final uncompressed bytes of its file with SHA-256 and write the digest as standard Base64 in hash. This applies even when deploying only original files. Rebuild and deploy the updated manifests together with their assets. See the Sample Vite plugin and its build configuration.

If using the Sample plugin, precompressAssets([]) keeps every original and emits a Brotli sidecar when compression reduces its size. For a Brotli-only deployment, set brotliOnly to true on each entry whose original you omit and deploy <file>.br. Other entries require the original file.

During loading, ViteManifest rejects manifests outside the resolved root and assets outside their output directory or missing from disk with ConfigurationException. Deploy manifests, originals, and sidecars as regular files. Their paths below the web root must be free of symbolic links and reparse points. Normal startup loads manifests during pipeline configuration. Temporary hosts and SkipValidation skip that eager check.

Keep manifests and referenced assets under the application's web root, and verify CSS and JavaScript loading after publish.

Missing manifests or unmatched entry names do not by themselves fail startup. An unresolved Vite script or stylesheet entry is omitted and replaced with an HTML comment in every environment, including Production. Verify that each referenced entry exists after the frontend build.

Disable the publish item injection when an application owns this behavior itself:

<PropertyGroup>
  <DrnHostingViteManifestPublishItemsEnabled>false</DrnHostingViteManifestPublishItemsEnabled>
</PropertyGroup>

Developer Diagnostics

Request logging and diagnostic buffering apply wherever HttpScopeMiddleware runs. Detailed exception pages and startup reports are Development features.

Development exception pages opt out of redaction for their log viewer and request details, including headers, cookies, URLs, route values, and buffered bodies. The log viewer uses ScopedLog.GetLogs(redact: false). Emitted diagnostics remain redacted, while scope events retain their contents. Diagnostic capture limits, [IgnoreLog], HTML encoding, access rules, and configuration debug-view protections remain active. Keep these pages and saved startup reports private.

Failures while generating startup reports record the exception type, stack trace, and fixed ReportGenerationFailed category in scoped diagnostics. Their exception messages are omitted.

Logging conventions

EventId is provided by .NET's Microsoft.Extensions.Logging. It holds a numeric ID and an optional name. Use it with a public static <Module>LogEvents catalog. For example, HostingLogEvents.MfaAuthorizationChallenge carries ID 7401 and name MfaAuthorizationChallenge.

  • Define events as public static readonly EventId fields in the owning module's Logging namespace.
  • Give each event a descriptive name and an ID unique within its module. Do not renumber, rename, or reuse published events for different meanings.
  • Filter dedicated logs by logger category and event ID. Numeric IDs are not globally unique across applications or libraries.
  • Use ScopeEvent and IScopedLog.WithEvent instead of event dictionaries. Standard fields are EventId, EventName, EventOutcome, and EventReason.
  • Consumers can define a companion catalog, such as SampleLogEvents. Reuse Hosting definitions only for the same event meaning.

Use IScopedLog for request and operation diagnostics. Direct ILogger calls are appropriate for scope flushing, bootstrap failures, and dedicated audit events. Keep request audit decisions in the scoped log too. Dedicated audit events must not include the full request log.

Every ScopedLog has a stable CorrelationId. Its TraceId is captured from an active W3C activity, or left absent. HTTP TraceIdentifier remains separate. LogScoped emits the primary event ID with the aggregate. Dedicated audit records use EventOutcome, EventReason, nullable TraceId, and CorrelationId. See Utils OpenTelemetry correlation.

Startup Exception Reports

In Development, if the application fails during RunAsync, DRN Hosting attempts to write StartupExceptionReport.html beside the application assembly. Report generation is best effort; when no report can be created, use the startup logs. Production and staging use normal startup logs only.

When generated, the report can include:

  • Full stack traces with source code highlighting (if symbols available).
  • Environment details and configuration snapshots.
  • Scoped logs leading up to the crash.

API Failure Responses

DRN Hosting returns application/problem+json for API failures with any 4xx or 5xx status (400 through 599). This covers MVC and typed problems, validation, exceptions, and empty authentication, authorization, rate-limit, and missing-route responses. The format applies in every environment, regardless of the Accept header.

Responses include type, title, numeric status, instance, and requestId. The status matches the HTTP status. requestId comes from HttpContext.TraceIdentifier and matches the request reference in scoped logs. instance defaults to PathBase + Path, without the query string. Validation keeps its errors dictionary. Explicit problem details and extensions are preserved. Generic exception responses omit exception messages, stack traces, headers, and request bodies.

[ApiController] endpoints and endpoints with ASP.NET Core API metadata use this format. For minimal endpoints without inferred API metadata, add .DisableCookieRedirect(). Configure path prefixes to identify unmatched API routes and routing-generated 405 responses:

using DRN.Framework.Hosting.Middlewares.ApiErrors;

services.Configure<DrnApiErrorOptions>(options => options.PathPrefixes = ["/Api"]);

Prefixes default to an empty array. Matching is case-insensitive, respects PathBase, and follows path segments: /Api does not match /Apiary. Prefixes cannot contain a trailing slash, query, fragment, or relative segment. Invalid prefixes fail startup validation. Prefixes and Accept headers do not reclassify matched browser endpoints. Sample and Nexus configure /Api.

Authentication, cookie redirects, and fallback authorization remain unchanged. Responses preserve WWW-Authenticate, cookies, and Retry-After. Use AddProblemDetails(options => options.CustomizeProblemDetails = ...) to customize MVC-generated and typed problems. This callback does not run for DRN's generic exception or empty-error responses; use ScopeContext.Problem for defaults shared across those paths. Include only public information in custom fields.

API Problem Details use SharedKernel JsonConventions.DefaultOptions, including camelCase properties, string enums, and precision-safe 64-bit integers. MVC AddJsonOptions and ConfigureHttpJsonOptions overrides do not apply to these responses.

Leave Type unset for routine failures. Both throw ExceptionFor.NotFound(...) and ScopeContext.Problem.NotFound(...) produce NotFoundException.Status = 404. Hosting sets that HTTP status and infers ASP.NET Core's standard problem type and title. Type precedence is existing response, scoped value, status default, then about:blank. Define a stable custom type only when clients need to distinguish a condition beyond HTTP status; changing it changes the public contract.

Failure HTTP status Default problem type
ScopeContext.Problem.NotFound(...) 404 https://tools.ietf.org/html/rfc9110#section-15.5.5
ScopeContext.Problem.Conflict(...) 409 https://tools.ietf.org/html/rfc9110#section-15.5.10
Unmapped exception 500 https://tools.ietf.org/html/rfc9110#section-15.6.1

Prefer an existing semantic base for custom exceptions. ConflictException subclasses inherit 409; direct DrnException subclasses use the supplied status or default to 500. See inheritance examples.

HttpScopeMiddleware selects the status from the caught exception in this order:

Exception matched HTTP status
DrnException, including subclasses Its declared Status
FlurlHttpException, including subclasses Uses the upstream HTTP status mapping below
BadHttpRequestException, including subclasses Preserves its StatusCode exactly: 400 when constructed without an explicit status, otherwise the constructor-supplied status
Any other exception 500

For incoming request errors, new BadHttpRequestException("Invalid request") yields 400; supplying 413 or 500 preserves that exact status. Server-level rejections outside DRN middleware need not use DRN formatting.

For Flurl, "upstream" is the service called by the outbound request. GetGatewayStatusCode() maps exception.StatusCode as follows:

Upstream status on the exception Application response status
Any status from 400 through 499 The same status, including 401, 403, 404, 408, and 429
503 Service Unavailable 503 Service Unavailable
504 Gateway Timeout 504 Gateway Timeout
Any other status, including 500, 501, and 502 502 Bad Gateway
No status (null), such as a connection failure or timeout without an HTTP response 502 Bad Gateway

Thus a timeout without an upstream response maps to 502, not 504. Only the status is preserved, not upstream bodies or headers.

Mapping uses the caught exception, not its name, message, Category, or inner exception. An ordinary wrapper around a DRN exception therefore defaults to 500. Setting Type alone does not change status. Exception messages remain private.

These rules apply before the response starts, with cancellation handled separately. Invalid statuses, including MaliciousRequestException, abort. Problem formatting requires eligible API or opted-in HTMX requests and respects endpoint opt-outs; ordinary browser navigation uses HTML errors.

Set only the public error defaults that need additional context before returning an error or throwing a DRN exception:

using DRN.Framework.SharedKernel;
using DRN.Framework.Utils.Scope;

ScopeContext.Problem.Detail = "A tag with this name already exists.";
ScopeContext.Problem.Extensions["code"] = "tag_already_exists";
ScopeContext.Problem.Conflict("Duplicate tag detected during creation.");
// same as: throw ExceptionFor.Conflict("Duplicate tag detected during creation.");

The same shorthand is available for every ExceptionFor factory. Helpers throw immediately and hide their frames from formatted stack traces.

This returns 409 Conflict with the public detail and code. The exception message stays private. Type, Title, and Instance can also be set on ScopeContext.Problem. Existing response fields and extension keys take precedence, including titles and types already generated by ASP.NET Core. Scoped defaults fill only null fields and missing extension keys. Standard field names and errors are reserved extension keys. This lazy, request-wide object holds one error context; do not use it for separate concurrent errors. See scope usage.

Swagger adds one representative 400 response as application/problem+json with required requestId. Its description explains that the same contract covers all 4xx and 5xx statuses. Other statuses are shown only when declared by the endpoint. Declared validation schemas and custom response types are preserved. Declare custom error bodies with ProducesResponseType or minimal API response metadata so Swagger can describe them accurately. Browser and HEAD operations are unchanged.

Apply [DisableDrnProblemDetails] from DRN.Framework.Hosting.Middlewares.ApiErrors to a controller class or individual action to disable DRN formatting and automatic Swagger error metadata. The attribute is inherited. ASP.NET Core may still produce native Problem Details, including validation responses, without DRN's requestId. Exceptions use the existing development diagnostics or production fallback. Authentication and authorization remain unchanged. Unmatched routes still use the configured path prefixes because no endpoint attribute is available.

Migration: Clients must handle JSON where API errors previously returned text, HTML, or no body. Validation gains requestId. For these statuses, WriteProductionErrorResponseAsync handles browser, non-API, and opted-out API exceptions. Browser error pages and development diagnostics are unchanged.

Custom nonempty bodies are not rewritten. Empty-response handling respects declared content type and length, and disabled status-code pages. HEAD responses have no body. Responses that have started, aborted requests, and errors produced before the application pipeline are outside this contract.

HTMX Partial Requests

Opt in to the same public Problem Details contract for failed HTMX requests, including Razor page handlers:

services.Configure<DrnApiErrorOptions>(options => options.HandleHtmxRequests = true);

HandleHtmxRequests defaults to false. When enabled, requests with exactly one HX-Request: true header receive the API failure contract for exceptions, eligible empty 4xx/5xx responses, and explicit Problem Details in every environment. This includes preserved status codes, request references, public validation errors, and redacted exception responses.

Authentication, cookie redirects, endpoint opt-outs, and custom non-problem bodies retain their existing behavior. Normal navigation uses browser error pages and Development diagnostics. Opted-in HTMX exceptions return Problem Details instead of invoking WriteProductionErrorResponseAsync or displaying the Development exception page.

Razor handlers choose validation representation explicitly. Page() with invalid ModelState retains HTML. To select JSON, return an ObjectResult containing ValidationProblemDetails(ModelState) with status 400 or 422. Use safe public messages, exact posted field names, and an empty key for form-level errors. The browser client must present Problem Details as data and explicitly support any HTML validation swaps. See the Sample error handling conventions for examples.

Custom Error Pages

The framework includes built-in Razor Pages for developer-time exception handling:

  • RuntimeExceptionPage: Detailed breakdown of unhandled exceptions with request state and logs.
  • CompilationExceptionPage: Visualizes Razor or code compilation errors with line-specific highlighting.

Production responses and eligible API/HTMX Problem Details skip diagnostic model collection when no post-creation exception filter needs the model. Pre-creation filters still run before response selection. Registered post-creation filters retain the populated model and their existing order, unless a pre-filter sets SkipPostCreationFilter. Development HTML diagnostics and explicit GetExceptionPageModel calls still create the model.

Configure application-owned error pages with Hosting's DrnErrorPageOptions:

services.Configure<DrnErrorPageOptions>(options =>
{
    options.ServerErrorPage = Get.Page.Root.SomethingWentWrong;
    options.NotFoundPage = Get.Page.Root.NotFound;
    options.BadRequestPage = Get.Page.Root.BadRequest;
});

The types are in DRN.Framework.Hosting.Middlewares.ExceptionHandler. Use Razor page names under Pages, without .cshtml. Each option defaults to null, independently disabling that custom page. Invalid page-name syntax fails options validation at startup.

The application's Razor page uses @model DRN.Framework.Hosting.Middlewares.ExceptionHandler.ServerErrorPageModel. This anonymous, non-cacheable model exposes only RequestId and returns HTTP 500 on direct GET requests. Keep its content generic and use a layout that does not require authentication or depend on application data.

Hosting renders the configured page internally for Staging/Production browser 5xx exceptions and bodyless HTML 5xx responses, preserving the status, request reference, and deployment prefix. It requires an explicit text/html Accept value and excludes API requests described above. Browser Development exception diagnostics remain unchanged. Browser rendering failures before the response starts fall back to redacted plain text.

NotFoundPage uses @model DRN.Framework.Hosting.Middlewares.ExceptionHandler.NotFoundPageModel. This anonymous, non-cacheable model returns 404 on direct GET. Hosting renders it for bodyless browser HTML 404 responses and Staging/Production browser exceptions mapped to 404, preserving the status without redirecting. Existing response bodies remain unchanged. API failures use Problem Details JSON. Missing routes still pass through the application's authorization and fallback policies before they can return 404; the option does not bypass authentication.

BadRequestPage uses BadRequestPageModel and follows the same opt-in HTML rendering rules for bodyless browser 400 responses and Staging/Production browser exceptions mapped to 400. Direct GET requests return 400. API validation retains its errors and gains the common request reference. Existing validation messages and browser Development exception diagnostics remain unchanged.

All three models expose RequestId from HttpContext.TraceIdentifier. Internally rendered pages retain the original request's reference; direct visits use the page request's reference. Display it as a request reference for support, without exception details.

For other browser response formats, derive from DrnExceptionHandler, register it for IDrnExceptionHandler, and override WriteProductionErrorResponseAsync(HttpContext). Preserve the HTTP status and omit exception details. Supported API failures use the shared JSON contract described above.

For a 403 page, use @model DRN.Framework.Hosting.Middlewares.ExceptionHandler.AccessDeniedPageModel. It allows anonymous access and disables caching. To preserve the denied request's reference across a cookie redirect, configure the application cookie after registering Identity and assigning other redirect callbacks:

services.ConfigureApplicationCookie(options =>
{
    options.AccessDeniedPath = "/AccessDenied";
    options.Events.PreserveAccessDeniedRequestId();
});

PreserveAccessDeniedRequestId() is in the same namespace and requires MVC TempData services. It preserves the existing callback and stores the reference only for 302 redirects, leaving API 401/403 responses unchanged. AccessDeniedPageModel returns 403 on GET and consumes the stored reference once; direct visits otherwise use their own HttpContext.TraceIdentifier. This is separate from DrnErrorPageOptions status-page rendering. If the cookie scheme uses EventsType, call the extension on that events instance instead of options.Events.

Request Body Buffering

Diagnostic capture retains HTTP status, authentication outcome, and rate-limit metadata. Request_IpAddress records the remote IP as text or an empty string. Nonempty l5d-client-id headers are logged directly. Backend runtime does not match names or configured paths, including request query/form names. Explicit classifications and capture bounds remain authoritative. Rate-limit rejection identifiers retain separate protection. SharedKernel analyzers check statically known names and project paths. Scoped logs preserve classification metadata for redacted reads. See the diagnostic contract.

Request diagnostics buffer POST, PUT, and PATCH bodies only when Content-Length is known and within the configured limit. Kestrel request-size limits still apply.

Apply the application responsibilities for dynamic data when capturing request values.

Scoped HTTP diagnostics, startup reports, and developer-page copies use the central diagnostic policy. Explicit classifications control redaction; explicit URLs still remove credentials. Text remains bounded without content scanning. Original exception/context objects remain available to filters and DiagnosticSource subscribers, which own their export policy. Classify typed members and dictionary entries explicitly. This does not add body capture or change public Problem Details.

Configuration via DrnAppFeatures (in appsettings.json):

Key Type Default Effect
DisableRequestBuffering bool false Disables this diagnostic buffering feature
MaxRequestBufferingSize int 0 (uses 30,000) Max bytes to buffer. Values below 10,000 use the 30,000-byte fallback
{
  "DrnAppFeatures": {
    "DisableRequestBuffering": false,
    "MaxRequestBufferingSize": 50000
  }
}

Skipped reads return a reason, such as an unknown Content-Length or a length above the configured byte limit.

Modern HTTP Standards

HttpScopeMiddleware applies these defaults to responses passing through the request scope:

  • 303 See Other: Middleware converts 302 Found to 303 See Other. For example, a redirect after form submission uses GET for the destination. Use 307 or 308 when the destination must preserve the request method.
  • Secure Caching Default: Dynamic responses that do not set their own Cache-Control receive no-store, no-cache, must-revalidate. Explicit response caching directives take precedence, while static assets opt into public caching.

Static Asset Compression

Deploy the files declared by each Vite manifest. Use ViteManifestItem.BrowserPath for the deployed URL and Path for the logical original path. Script, stylesheet and preload TagHelpers link directly to the Brotli file when present at manifest load, or to the original otherwise. Direct Brotli URLs require a Brotli-capable browser. The URL includes the request path base, and subresource integrity uses the build-time hash of the decoded bytes. ASP.NET Core static files serve the compressed bytes with Content-Encoding: br and the original media type.

The Sample Vite build uses Brotli quality 11. DRN serves original assets, Razor HTML and API JSON without runtime compression on HTTP and HTTPS. Original and Brotli assets have separate URLs and can be cached independently.

Local Development Infrastructure

Use DRN.Framework.Testing to provision Postgres during local Development without manual Docker management. The following setup keeps Testcontainers dependencies in Debug builds and explicitly enables local dependency launch.

1. Add the Debug-Only Package

NuGet consumers should reference the DRN.Framework.Testing version matching DRN.Framework.Hosting:

<ItemGroup Condition="'$(Configuration)' == 'Debug'">
    
    <PackageReference Include="DRN.Framework.Testing" Version="VERSION" />
</ItemGroup>

Repository contributors may use the sibling project reference instead.

2. Enable External Dependency Launch

Add the explicit opt-in to appsettings.Development.json:

{
  "DrnDevelopmentSettings": {
    "LaunchExternalDependencies": true
  }
}

External dependencies launch only for a Development host with this setting enabled. Test and temporary hosts are excluded.

3. Configure Startup Actions

Implement DrnProgramActions to launch the configured local dependencies.

#if DEBUG
using DRN.Framework.Testing.Extensions;

public class SampleProgramActions : DrnProgramActions
{
    public override async Task ApplicationBuilderCreatedAsync<TProgram>(
        TProgram program, WebApplicationBuilder builder,
        IAppSettings appSettings, IScopedLog scopedLog)
    {
        var options = new ExternalDependencyLaunchOptions
        {
            PostgresContainerSettings = new() 
            { 
                Reuse = true, // Faster restarts
                HostPort = 6432 // Avoid conflicts with local Postgres
            }
        };

        // When enabled, starts missing containers and updates AppSettings.
        await builder.LaunchExternalDependenciesAsync(scopedLog, appSettings, options);
    }
}
#endif

Hosting Utilities

IAppStartupStatus

Singleton gate for background services that need to wait until the host has fully started before executing.

using DRN.Framework.Hosting.Utils;
using DRN.Framework.Utils.DependencyInjection.Attributes;
using Microsoft.Extensions.Hosting;

[HostedService]
public sealed class MyWorker(IAppStartupStatus startupStatus) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        if (!await startupStatus.WaitForStartAsync(stoppingToken))
            return;

        // The application has started.
    }
}

[HostedService] is discovered when the worker's assembly is registered with AddServicesWithAttributes().

IServerSettings

Resolves bound server addresses from Kestrel. Normalizes wildcard hosts (0.0.0.0, [::], +, *) to localhost for internal self-requests. Prefers HTTP over HTTPS to avoid TLS overhead.

using DRN.Framework.Hosting.Utils;

public class MyService(IServerSettings server)
{
    public void LogAddresses()
    {
        var loopback = server.GetLoopbackAddress();   // e.g. "http://localhost:5988"
        var all = server.GetAllAddresses();            // All normalized bound addresses
    }
}

Global Usings

Suggested global usings for Hosted applications to reduce boilerplate:

global using DRN.Framework.Hosting.DrnProgram;
global using DRN.Framework.Hosting.Endpoints;
global using DRN.Framework.Utils.DependencyInjection;
global using DRN.Framework.Utils.Logging;
global using DRN.Framework.Utils.Settings;
global using Microsoft.AspNetCore.Mvc;

For complete examples, see Sample.Hosted.


Documented with the assistance of DiSC OS


Semper Progressivus: Always Progressive

Commit Info

Author: Duran Serkan
Date: 2026-11-08 18:49:03 +0300
Hash: 6a940306241f0059fb06eb65d59a16ab8a248725

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on DRN.Framework.Hosting:

Package Downloads
DRN.Framework.Testing

DRN.Framework.Testing package encapsulates testing dependencies and provides practical, effective helpers such as resourceful data attributes and test context. This package enables a new encouraging testing technique called as DTT(Duran's Testing Technique). With DTT, any developer can write clean and hassle-free unit and integration tests without complexity. ## Commit Info Author: Duran Serkan Date: 2026-11-12 20:55:19 +0300 Hash: 257259c2ac6a6311975a3c26ece133daa31f0b12

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.11.0-preview001 86 11/12/2026
0.10.1-preview008 88 11/8/2026
0.10.1-preview007 96 11/4/2026
0.10.1-preview006 111 10/27/2026
0.10.1-preview005 111 10/25/2026
0.10.1-preview004 135 10/14/2026
0.10.1-preview003 115 10/4/2026
0.10.1-preview002 107 10/4/2026
0.10.1-preview001 107 10/4/2026
0.10.0 135 9/20/2026
0.10.0-preview004 120 9/19/2026
0.10.0-preview003 120 9/13/2026
0.10.0-preview002 219 9/9/2026
0.10.0-preview001 166 9/7/2026
0.9.9-preview004 131 8/27/2026
0.9.9-preview003 123 8/26/2026
0.9.9-preview002 126 8/20/2026
0.9.9-preview001 137 8/16/2026
0.9.8 181 8/12/2026
0.9.8-preview004 141 8/12/2026
Loading failed

## Version 0.10.1

### Changed

*   **Request Diagnostics**: Request values use bounded capture. `Request_IpAddress` is recorded as an empty string when no remote address is available. Empty `l5d-client-id` headers are omitted.

*   **Development Exception Pages**: Display unredacted scoped logs and request details within capture limits and `[IgnoreLog]` exclusions. Emitted logs and views outside Development remain redacted.

*   **Diagnostic Redaction**: HTTP and startup logs redact explicitly classified data within capture limits. Backend capture does not infer classification from names, including configured field paths and URL/query/form names. Applications must classify dynamic data explicitly. URL processing removes credentials and validates encoding. Callbacks can still receive raw objects and must keep private diagnostics out of public responses.
*   **Rate Limit Defaults**: Post-auth buckets now allow 250 tokens per user and pre-auth buckets allow 2,500 tokens per IP, with matching refills every 60 seconds. Explicit settings override these defaults.
*   **Rate Limit Diagnostics**: Rejection logs include the rule action, distinguishing limiter rejections from explicit deny rules and unattributed rejections, consistent with rate-limit metrics.

### Breaking Changes

*   **Runtime response compression removed**: DRN serves dynamic responses and original assets uncompressed on HTTP and HTTPS. Remove overrides of `ConfigureResponseCompressionOptions`, `ConfigureCompressionProviders`, `ConfigureBrotliCompressionLevel` and `ConfigureGzipCompressionLevel`. Configure asset compression in the frontend build.
*   **Vite manifests and compression**: Before upgrading, add a build step that writes the Base64 SHA-256 `hash` of each entry's uncompressed bytes, then rebuild all manifests. Original-only deployments also require hashes. Entries marked `brotliOnly` require only their `.br` file. Other entries require the original asset. Deploy manifests and assets on paths without symbolic links below the web root. Razor links to a deployed Brotli variant when available. These URLs require native HTTP Brotli decoding (`Content-Encoding: br`) and a browser version that still receives vendor security updates. Startup pre-warming and its public proxy, factory, and report types, including `IViteManifest.WarmReport`, have been removed.
*   **Identity Management API**: `IdentityManagementControllerBase` now uses API controller behavior. Derived controllers must use attribute routes. Invalid request models return validation Problem Details before the action runs, and cookie authentication failures return 401 or 403 instead of redirects.
*   **API Failure Responses**: API failures for all 4xx and 5xx statuses now use `application/problem+json` in every environment by default. Clients must handle JSON instead of text, HTML, or empty responses. Problems include `requestId` and retain validation errors and public extensions. Serialization uses SharedKernel JSON conventions instead of MVC or HTTP JSON overrides. Configure `DrnApiErrorOptions.PathPrefixes` for unmatched API routes. Browser pages, authentication and retry headers, and custom nonempty bodies are unchanged. For these statuses, `WriteProductionErrorResponseAsync` handles browser, non-API, and opted-out API exceptions.
*   **Diagnostic Page Routing**: `DeveloperView` paths no longer trigger diagnostics before authentication. Protect pages that display sample errors with an authorization policy. Replace the removed two-argument `ExceptionPageAccessor.IsExceptionPage` overload with `IsExceptionPage(path)`. Internal exception templates still block direct access.

### New Features

*   **HTMX Error Responses**: Enable `DrnApiErrorOptions.HandleHtmxRequests` to use the API Problem Details contract for failed HTMX requests, including Razor handlers. Disabled by default. Authentication, normal navigation, endpoint opt-outs, and custom non-problem bodies retain their existing behavior.
*   **Scoped Problem Details**: API errors accept public defaults from `ScopeContext.Problem`, preserving existing response values. `instance` defaults to the request path including deployment prefixes and excluding query strings. Exception messages remain private.
*   **API Error Opt-Out**: Apply `[DisableDrnProblemDetails]` to a controller or action to retain native or application-owned error responses and skip automatic Swagger error metadata. Authentication and authorization are unchanged.
*   **API Error Metadata**: Swagger adds one representative 400 Problem Details response with required `requestId` and a description covering all 4xx and 5xx statuses. Other declared statuses, validation schemas, and custom response types are preserved.
*   **Custom Browser Error Pages**: `DrnErrorPageOptions` supports application-owned Razor pages for 5xx, 404, and 400 errors. Pages preserve status codes, expose `RequestId`, and have a redacted fallback. Custom pages are disabled by default. See [custom error pages](README.md#custom-error-pages) for setup and other browser response customizations.
*   **Access-Denied Request References**: Use `AccessDeniedPageModel` with `CookieAuthenticationEvents.PreserveAccessDeniedRequestId()` to retain the original request reference across cookie redirects. Access-denied pages support anonymous access and are not cached.
*   **Swagger Authorization**: Added `DrnProgramSwaggerOptions.AuthorizationPolicy` to protect Swagger UI, its assets, and OpenAPI documents with an application-owned named policy. Applications can enable Swagger in Staging and Production while retaining role and MFA requirements. Development-only enablement remains the framework default.
*   **Endpoint URL Generation**: Added `Url.Endpoint(ApiEndpoint, values)` to generate request-aware MVC URLs from endpoint accessors. It preserves deployment prefixes, uses effective MVC action names and destination areas, and reports uninitialized or ambiguous metadata and failed URL generation explicitly. Existing `Path(...)` APIs remain compatible.
*   **Application URLs**: Added `HttpRequest.ApplicationUrl` for application-owned route paths and `ApplicationUrlTagHelper` for `~/` HTML and HTMX URLs. Deployment prefixes are preserved without changing controller route prefixes or already-resolved URLs.

### Bug Fixes

*   **Developer Exception Pages**: Panel controls follow document focus order, support Enter and Space, and announce the active panel to assistive technology. Exception pages include a favicon.

*   **Exception Details Serialization**: Prevent exception handling from failing during initialization after shared JSON options have already been used for serialization.

*   **Started Response Exceptions**: `HttpScopeMiddleware` now logs and rethrows the original exception when `context.Response.HasStarted`, instead of failing while assigning the response status code.
*   **Page Rendering**: `IPageUtils.RenderPageAsync` now supports standard `_ViewStart` files, layouts, and endpoint-generated links even for unmatched requests. Rendering also awaits scoped-service cleanup on success or failure.
*   **Developer JSON Viewer**: Updated bundled JSONEditor to 10.4.3 and corrected dark-theme search highlighting. Fixed Ace and color-picker styles blocked by the default CSP on runtime exception pages. The read-only log viewer omits the Repair JSON action and skips the validation worker.

*   **Redirects**: Fixed errors when converting started redirects to HTTP 303 and corrected the logged response status.
*   **Deployment Prefixes**: Swagger URLs, developer error-page assets, active navigation, login/MFA redirects, and Vite assets now support deployment prefixes. Swagger uses processed request values rather than raw forwarded headers. Unauthorized redirects preserve the public return path and query string. Active href links support custom routes and exclude external URLs and paths outside the deployment prefix. Use `asp-page` for page-identity matching.

---

Documented with the assistance of [DiSC OS](https://github.com/duranserkan/DRN-Project/blob/develop/.agent/rules/DiSCOS.md)

---
**Semper Progressivus: Always Progressive**