DRN.Framework.Hosting
0.11.0-preview002
Prefix Reserved
dotnet add package DRN.Framework.Hosting --version 0.11.0-preview002
NuGet\Install-Package DRN.Framework.Hosting -Version 0.11.0-preview002
<PackageReference Include="DRN.Framework.Hosting" Version="0.11.0-preview002" />
<PackageVersion Include="DRN.Framework.Hosting" Version="0.11.0-preview002" />
<PackageReference Include="DRN.Framework.Hosting" />
paket add DRN.Framework.Hosting --version 0.11.0-preview002
#r "nuget: DRN.Framework.Hosting, 0.11.0-preview002"
#:package DRN.Framework.Hosting@0.11.0-preview002
#addin nuget:?package=DRN.Framework.Hosting&version=0.11.0-preview002&prerelease
#tool nuget:?package=DRN.Framework.Hosting&version=0.11.0-preview002&prerelease
DRN.Framework.Hosting
Application shell for DRN web applications with security-first design, structured lifecycle, and type-safe routing.
TL;DR
- Security defaults:
DrnDefaultsenforces MFA, nonce-based script CSP, and HSTS outside Development. - Startup:
DrnProgramBaseprovides hooks for registration, middleware, and validation. - Routing: Typed controller endpoint accessors bind to mapped routes; page accessors generate Razor paths.
- Local infrastructure:
DRN.Framework.Testingprovides opt-in Postgres provisioning. - Frontend: Razor TagHelpers handle Vite manifests, CSP nonces, and HTMX CSRF headers.
Table of Contents
- QuickStart: Beginner
- QuickStart: Advanced
- Lifecycle & Execution Flow
- DrnProgramBase Deep Dive
- Configuration
- Security Features
- Source-Known Controllers
- Endpoint Management
- Razor TagHelpers
- Developer Diagnostics
- API Failure Responses
- Modern HTTP Standards
- Static Asset Compression
- Local Development
- Hosting Utilities
- Global Usings
- Related Packages
QuickStart: Beginner
Use a .NET 11 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 |
|---|---|
ConfigureEndpointCollection |
Returns the program's typed endpoint singleton for startup binding. Defaults to no typed controller accessors. |
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). |
Swagger serves OpenAPI 3.2 documents by default. If a client generator or validator requires 3.1, set options.ConfigureSwaggerEndpointOptionsAction = endpoint => endpoint.OpenApiVersion = Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_1; in ConfigureSwaggerOptions.
When AddSwagger is enabled, set AddSwaggerUI = false to expose only the OpenAPI document. AddSwagger = false disables both.
Swagger UI resolves its default document URL from the configured OpenAPI route and preserves deployment prefixes. An explicit URL list supplied through ConfigureSwaggerUIOptionsAction takes precedence.
The browser-tab title defaults to the API title and version, for example DRN Sample (v1). Set Title to override it. Swagger UI preserves Swashbuckle's default caching behavior. ConfigureSwaggerUIOptionsAction can override DocumentTitle, CacheLifetime and the route prefix. Set CacheLifetime = null in that callback to disable UI caching explicitly. Prefixes accept nonempty segments of ASCII letters, digits, hyphens and underscores. Surrounding slashes are trimmed. Root mounts are rejected.
Set DrnPageOptions.FaviconUrl to a host-served application-root-relative image path, such as /images/icon.svg, to customize the Swagger UI tab icon. Deployment prefixes and nested UI routes are preserved. Remote URLs, query strings and traversal segments are rejected. Null keeps the default icon.
For controller actions that accept [FromQuery] PaginationRequest or [FromQuery] PaginationResultInfo, Swagger omits calculated fields and marks defaulted page size and cursor inputs as optional. Continuation requests retain their outer total-count fields. Both cursor ID descriptions explain when to supply the first and last IDs from the previous page. JSON bodies preserve required members. Result descriptions distinguish the returned page's outer IDs from the previous-page cursor in its request.
Hosting adds generic operation guidance for query and body pagination inputs and PaginationResultModel<T> responses. Query fields retain explicit prefixes, such as previous.FirstId. Body guidance uses the actual names of any query parameters, including renamed parameters. Existing endpoint descriptions are preserved before the shared guidance. Keep application-specific ceilings, ignored settings and jump limits in the controller's EndpointDescription. Hosting does not infer those policies from a parameter type or HTTP method.
DRN JSON APIs accept the full signed 64-bit range as JSON integers or decimal strings, including quoted small values such as "42". DRN writes a number within JavaScript's safe integer range (inclusive) and a string outside it. Nullable values also allow JSON null, including controller parameters declared as [FromBody] long? in the generated request schema. Required validation metadata, such as [Required], excludes null from those body schemas.
The default bearer security requirement excludes operations marked with [AllowAnonymous] on the action or controller.
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. When null, all documentation endpoints use the application's fallback authorization policy. 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.
appsettings.jsonappsettings.{Environment}.json- User Secrets when the application assembly can be loaded
- Environment Variables (
ASPNETCORE_,DOTNET_, then unprefixed) - Mounted Directories (default:
/appconfig) - 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
KnownIPNetworkslist replaces the network defaults.KnownProxiesadds 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
AccessTokenResponsecontaining the setup access token,ExpiresIn = 300, and an emptyRefreshToken.
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, andblob: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
NonceTagHelperbelow 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, COEPcredentialless, and CORPsame-site. - PermissionsPolicy: Secure default directives with fullscreen limited to self.
Cookies and consent
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 matchingPolicyNamecompose 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
- ASP.NET Core rate limiting middleware
- RateLimiterOptions API
- RateLimitPartition API
- HybridCache library in ASP.NET Core
- Distributed caching in ASP.NET Core
- Redis token bucket rate limiter with .NET
- RFC 6585 Section 4: 429 Too Many Requests
- RFC 9110: Retry-After header
Source-Known Controllers
Use DRN.Framework.Hosting.Controllers to expose a filtered ISourceKnownRepository<TEntity> through DTOs. Choose one of three abstract controller variants:
| Base | Behavior |
|---|---|
SourceKnownController<TEntity, TDto, TCreateRequest> |
Combines all read actions with create/delete actions. |
SourceKnownReadOnlyController<TEntity, TDto> |
Exposes only bounded read actions. |
SourceKnownWriteOnlyController<TEntity, TDto, TCreateRequest> |
Exposes only create/delete HTTP actions. |
All variants share SourceKnownControllerBase<TEntity, TDto>, which implements ISourceKnownService<TEntity> and provides repository access, protected DTO mapping and cancellation helpers without HTTP actions. The combined controller inherits the read-only controller and adds writes. The write-only controller inherits the combined controller and seals [NonAction] overrides for all reads. Those methods remain callable from C#, but are excluded from HTTP routing and API discovery.
TEntity derives from AggregateRoot, TDto derives from Dto, and the create request is an application-owned class. Pass the repository to the constructor and implement ToDto. Concrete controllers supply [Route] and explicit named authorization policies. DRNAUTHORIZATION001 rejects exposed actions without a nonblank [Authorize(Policy = "...")] on the controller or action, including inherited policies. Bare [Authorize] and roles alone do not satisfy this rule. [AllowAnonymous] is rejected. DRN host MFA and rate-limiting policies still apply.
Register each named policy with ASP.NET Core authorization. Roslyn checks declarations, while ASP.NET Core enforces policies for HTTP requests. The analyzer cannot verify policy registration or resource permissions. Direct C# action calls do not execute MVC authorization. Applications must enforce tenant/resource visibility through repository filters and application code, including for counts and existence checks.
For custom attributes derived from AuthorizeAttribute, set the inherited Policy property explicitly. Constructor-inferred policies, hidden or remapped policy properties, and conditional attributes do not satisfy DRNAUTHORIZATION001. The rule also checks generated controllers. Use standard [Authorize(Policy = "...")] when a custom attribute cannot provide a statically verifiable declaration.
Read endpoints
Routes below are relative to the concrete controller route.
| Method | Route | Action | Result |
|---|---|---|---|
| GET | {id:guid} |
GetAsync |
One DTO. Missing records follow repository not-found behavior. |
| POST | Lookup |
GetManyAsync |
DTO array for a nonempty JSON GUID array. Missing IDs and ordering follow repository behavior. |
| GET | Any |
AnyAsync |
Whether any visible entity exists. |
| GET | Count |
CountAsync |
Number of visible entities. |
| GET | root | PaginateAsync |
Page from query-bound PaginationRequest. Omit it for the first page. |
| GET | Paginate |
PaginateWithOptionsAsync |
First page from flat PaginationOptions. |
| POST | Paginate |
PaginateWithBodyAsync |
Page from a JSON PaginationRequest, including continuation cursors. |
Pagination and batch sizes default to a server ceiling of 100. Override protected MaxPageSize and MaxBatchSize to change it within 1..1000. Callers cannot raise those ceilings. Pagination discards caller totals and refresh hints. UpdateTotalCount requests a server count. First requests start at page one, and continuation jumps are limited to ten pages from the supplied cursor. Use the returned Info navigation helpers to construct continuation requests. GUID operations retain the repository's configured format and validation. Every base action links request cancellation to the scoped repository before repository work.
Refresh results derive next-page availability from an extra fetched row. JSON null page-size or cursor members use the pagination defaults before the controller applies its limits.
Disable inherited endpoints
Every exposed action is virtual. Override it with MVC [NonAction] to remove it from routing and API discovery. For example, using the Sample application's tag types:
using DRN.Framework.Hosting.Controllers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Sample.Contract.QA.Tags;
using Sample.Domain.QA.Tag;
[Route("api/tags")]
[Authorize(Policy = "Tags.Read")]
public class ReadOnlyTagController(ITagRepository repository)
: SourceKnownReadOnlyController<TagEntity, TagDto>(repository)
{
protected override TagDto ToDto(TagEntity entity) => entity.ToDto();
[NonAction]
public override Task<long> CountAsync(CancellationToken cancellationToken = default)
=> base.CountAsync(cancellationToken);
}
[NonAction] prevents HTTP invocation, not direct C# calls. [ApiExplorerSettings(IgnoreApi = true)] only hides documentation and does not disable routing. A public override cannot be changed to internal. When using DRN typed endpoint accessors, omit ApiEndpoint properties for disabled actions so startup validation does not look for missing routes.
Opt in to writes
Derive from SourceKnownController<TEntity, TDto, TCreateRequest> to combine reads and writes, or SourceKnownWriteOnlyController<TEntity, TDto, TCreateRequest> for mutation endpoints alone. Implement protected CreateEntityAsync(request, cancellationToken) to construct the entity through application domain operations without saving it.
Use controller policies for common permissions and action policies for additional write permissions. Inherited controller and action policies combine. For resource-specific checks, override the action and call an application authorization service before calling the base action. Pass the request cancellation token to that service. Reject forbidden access with Forbid() where the result type permits, or ExceptionFor.Forbidden(...). Request-dependent creation checks may also live in application mapping/domain services. The framework does not supply mandatory authorization hooks.
PostAsync calls the repository's CreateAsync and returns HTTP 201 with the DTO. It does not generate a Location header, so disabling GetAsync does not break creation. DeleteAsync calls the GUID delete overload and returns HTTP 204 even when no matching record exists. The default EF repository performs a direct delete with repository filters and does not invoke entity deletion lifecycle hooks.
The base API actions do not require antiforgery tokens. For SPA APIs, explicitly select the application's registered bearer scheme in the named policies and require authentication. Do not add cookie or cookie/bearer composite schemes to their combined policies. The framework does not choose a handler name, and DRNAUTHORIZATION001 does not verify policy registration. For example, when using ASP.NET Core Identity bearer tokens:
builder.Services.AddAuthorizationBuilder()
.AddPolicy("Tags.Read", policy => policy
.AddAuthenticationSchemes(IdentityConstants.BearerScheme)
.RequireAuthenticatedUser())
.AddPolicy("Tags.Write", policy => policy
.AddAuthenticationSchemes(IdentityConstants.BearerScheme)
.RequireAuthenticatedUser()
.RequireClaim("permission", "tags.write"));
IdentityConstants is in Microsoft.AspNetCore.Identity; register the corresponding bearer handler in the application. Use the actual registered scheme for other bearer handlers. Send the token through the Authorization header. Cookie-authenticated Razor Pages and htmx requests retain antiforgery protection. If an application intentionally enables cookies for these API controllers, it must add antiforgery validation to mutations, for example with [AutoValidateAntiforgeryToken] on the concrete controller, and supply request tokens.
Overrides inherit MVC attributes. An override that does not call the base must preserve mapping, cancellation and persistence rules itself. Use [NonAction] on either write action to remove it independently. IgnoreApi actions still require a named policy because they remain routable.
Repository settings, raw identity conversion, expression predicates, staged Add/Remove, SaveChanges and cancellation-control methods are not HTTP endpoints. Unbounded GetAllAsync and PaginateAllAsync are not exposed. Updates and exports remain application-specific operations with their own domain and authorization rules.
Endpoint Management
DRN provides typed accessor members for controller endpoints and Razor Page identities. Controller endpoint accessors are bound to mapped routes and validated at startup. Razor Page accessors construct identity strings from member names and folders; keep them synchronized with page identities. A custom @page route does not change the page identity. For example, /HomeAnonymous can generate the URL /.
ApiEndpoint.EndpointName is an accessor label, not a registered route name. Use named-route generation only when the application's routing metadata actually registers that name. An action may have several route selectors; RouteEndpoints and RoutePatterns retain them all, while RoutePattern exposes the first pattern. Missing accessor bindings fail startup with a diagnostic pointing to application-part registration, action names and [NonAction] exclusions.
Url.Endpoint and GetUriByEndpoint reject MVC addresses shared by different controller types or CLR methods. A concrete signature binding does not make the controller/action/area address unique. Use distinct MVC names or areas, or generate links through explicitly registered route names. Multiple selectors for the same action remain supported, and link-suppressed routes do not introduce competing destinations.
Automatic hosted accessors
SDK Web hosts receive generated helpers automatically for eligible DRN programs. The generator is included with Hosting. Its buildTransitive target exposes it to direct and transitive package consumers. In this repository, the shared Directory.Build.targets import provides it to project-reference consumers, including transitive ones. Hosts do not need a separate generator reference. Source projects outside this shared build tree must import Hosting's build target once at their common build root, since MSBuild does not propagate analyzer items through project references.
The generator targets net10.0 because IDE compiler hosts can run on .NET 10 independently of a net11.0 application. It requires a .NET 10 or newer compiler host with compatible Roslyn 5.12 APIs. This does not lower the application target or change the solution SDK. If Rider cannot resolve generated roots, inspect its Roslyn worker logs for assembly-load errors and its Dependencies / Source Generators output. After rebuilding the generator, reload the solution so the IDE can load the updated assembly.
Generation requires SDK Web and a public, concrete, non-generic, top-level DRN program declared in that same project. Its inherited DrnProgramBase<TProgram> argument must be the program itself. For example, AppProgram : DrnProgramBase<AppProgram> qualifies, while a subclass of that closed program does not create another root. Referenced programs do not create roots in the consuming project. Non-Web projects do not generate helpers.
Every class deriving directly or indirectly from DrnProgramBase<TProgram> must end with the case-sensitive suffix Program. Diagnostic DRNHOSTING002 reports an error otherwise, including abstract, generic and nested descendants. HostedAccessors is no longer needed or available. Remove its assembly declarations and use the program's name and namespace for the generated roots.
If your diagnostic settings or suppressions use the earlier IDs, replace DRNHG001 with DRNHOSTING001 for accessor diagnostics and DRNHG002 with DRNHOSTING002 for program naming.
Return the generated singleton from the program's startup hook:
protected override EndpointCollection<AppProgram> ConfigureEndpointCollection()
=> Helpers.EndpointFor.AppEndpointFor.EndpointCollection;
Generated endpoint roots inherit EndpointCollectionBase<AppProgram, AppEndpointFor>. Their inherited EndpointCollection property creates the typed singleton directly. Page roots expose their typed PageCollection property in the same way. Reuse those singletons: generated group, page and endpoint properties return initialized values directly without a lookup or a new allocation on each access. Construction and startup binding still allocate. Keep the endpoint hook configured so startup binds and validates the generated controller accessors.
The namespace is always the program namespace plus .Helpers (Helpers for a global-namespace program). Roots are <ProgramStem>EndpointFor and <ProgramStem>PageFor, under .EndpointFor and .PageFor. Removing the final Program suffix gives the stem, so SampleProgram generates SampleEndpointFor and SamplePageFor. Program alone uses the stem App. Both roots are always generated. Razor Pages are detected automatically from @page directives in Razor AdditionalFiles using logical TargetPath metadata. Views, partials and Razor comments do not create page members. With no page inputs, the page root is empty and its PageCollection.All is empty.
Discovery uses compiler inputs, not a filesystem scan. Keep Razor compilation and AdditionalFiles enabled for hosts with pages. Missing inputs yield an empty collection; invalid logical paths on supplied pages still report DRNHOSTING001.
Programs in the same namespace share identical generated group and leaf type definitions. Each program keeps its own roots and accessor instances. Duplicate root names or conflicting definitions report DRNHOSTING001 before any sources for the conflicting program are emitted. Customize controller or group type names when programs need different definitions in the same namespace.
Local public, concrete, top-level, non-generic controllers deriving from ControllerBase and their eligible inherited actions are discovered automatically. MVC controllers without that ancestor are skipped because ControllerForBase<TController> requires it. Explicit mappings to unsupported controllers report DRNHOSTING001. Source-Known generic read/write bases are supported. Most-derived [NonAction] overrides exclude actions; IgnoreApi does not. Action members keep CLR method names, including Async; runtime metadata supplies effective MVC action names, areas and routes. Generated bindings include the concrete controller and CLR parameter types, independently of member aliases. No default route names are registered.
Generated accessors omit IDisposable.Dispose and IAsyncDisposable.DisposeAsync implementations, including inherited implementations and overrides. Separate methods with those names remain eligible. This does not change MVC routing. Apply [NonAction] to a public DisposeAsync implementation to exclude it from MVC actions as well.
Preserve host-specific groups with assembly declarations:
[assembly: AccessorGroup(typeof(AppProgram), "User.Identity", "UserIdentityFor")]
[assembly: AccessorController(typeof(AppProgram), typeof(ExceptionController),
TypeName = "ExceptionControllerFor")]
[assembly: AccessorController(typeof(AppProgram), typeof(RegisterController),
"User.Identity.RegisterController", TypeName = "UserIdentityRegisterFor")]
[assembly: AccessorMember(typeof(AppProgram), "Endpoint.User.Identity.RegisterController.ConfirmEmail", Name = "Confirm")]
AccessorController also explicitly includes referenced controllers. Omit its path when only a type name, route override or exclusion is needed. The path then follows the controller's relative Controllers namespace with a terminal Controller suffix removed. Explicit paths retain precedence. Its optional RouteTemplate preserves the legacy ControllerRoute property; runtime MVC still owns actual routes. Exclude = true on controller/member declarations retains manual control. Member paths start with Endpoint. or Page.. Group mappings apply to endpoint groups. Overloaded method names require exclusion and manual signature-bound accessors; unsupported declarations, collisions and stale configuration report DRNHOSTING001 with a remedy.
When RouteTemplate is omitted, legacy ControllerRoute metadata uses one distinct standard MVC [Route] template from the controller or its base classes. Multiple distinct templates, custom route providers or no template produce empty metadata. An explicit override wins, including RouteTemplate = "". Runtime routing remains authoritative. Keep repeated route templates in handwritten controller-owned constants and retain shared contract constants. Do not reference generator-produced constants from routing declarations.
Generated types are public partial classes. Keep custom members in authored partials. Explicitly exclude a generated member before replacing it manually. Keep Get handwritten to preserve other host helpers and initialization order. Generated hint paths are Helpers/PageFor/<full type name>.g.cs and Helpers/EndpointFor/<full type name>.g.cs. Generated code belongs to the compiler, not the physical project source directory. Optional compiler output belongs under obj; do not check it in.
Endpoint accessor paths support up to five group segments followed by the controller member, such as A.B.C.D.E.Items. Deeper paths report DRNHOSTING001; use a shorter AccessorController alias. Pages in folders or areas that are not C# identifiers can be excluded using their original path, such as Page.user-profile.Edit, and handled manually. Exclusions in valid groups preserve those groups for handwritten partial replacements.
Pages use file identities, not custom @page URLs. Root files group under Root; folders form nested groups. Area pages group under Areas.<Area> and the leaf group declares a static Area constant. Pass that area explicitly to Url.Page or tag helpers. Referenced Razor inputs must be explicitly supplied with their logical TargetPath. Generated page strings self-initialize; controller metadata binds during the existing per-program startup validation. Runtime-only MVC conventions remain usable through manual accessors and normal MVC routing. A generated action missing at runtime fails binding clearly.
Typed parameter/constraint generation remains a TODO. Continue passing route/query values to Url.Endpoint; runtime constraints and encoding remain authoritative. For absolute identity links use LinkGenerator.GetUriByEndpoint(HttpContext, endpoint, values), which shares effective-action and destination-area validation with Url.Endpoint and uses the processed request origin and PathBase.
1. Migrate existing accessors
Eligible SDK Web programs always generate both roots. An existing endpoint collection under another name produces DRNHOSTING001, even when the startup hook returns that collection. There is no root-name override or per-program generation opt-out. Changing only the old collection's base to EndpointCollectionBase<TProgram, TCollection> is insufficient.
For an Example.Hosted.AppProgram, migrate as follows:
- Remove every
HostedAccessorsassembly declaration, including itsNameandNamespaceoverrides. Rename DRN program descendants to end withProgram. - Replace references to the old roots with
Example.Hosted.Helpers.EndpointFor.AppEndpointForandExample.Hosted.Helpers.PageFor.AppPageFor. A program namedProgramuses these same root names. Other program names use their stem as described above. - Remove old root declarations when they contain only generated members. Move custom root members into public partial classes at the new names and namespaces. Remove the old base declarations, constructors that duplicate generated initialization, and generated group properties. Do not declare an
EndpointCollectionproperty on the endpoint root. - Move custom controller, group and page members into the corresponding generated partial classes. Remove declarations already supplied by generation, including controller constructors and page
PathSegmentsoverrides. UseAccessorController.TypeNameandAccessorGroupto retain leaf or group type names where needed. These aliases do not rename roots or change their namespaces. - Before retaining an authored replacement for a generated action or page, exclude that member with
AccessorMember. Keep endpoint bindings aligned with the CLR action signature, usingEndpointActionwhen needed. Exclusions affect accessor generation, not MVC routing or authorization. - Update the handwritten
Getfacade and return the generated endpoint singleton fromConfigureEndpointCollection. Remove obsolete collections after moving their customizations.
For example, this declaration preserves Get.Endpoint.User.Login and Get.Endpoint.User.Profile for a local UserController with eligible Login and Profile actions. Put assembly attributes before namespace and type declarations:
using DRN.Framework.Hosting.Endpoints;
using Example.Hosted;
using Example.Hosted.Controllers;
[assembly: AccessorController(typeof(AppProgram), typeof(UserController), "User", TypeName = "UserEndpoints")]
Keep the facade in an authored file. With Pages/User/Login.cshtml containing @page, the generated page root supplies User.Login:
namespace Example.Hosted;
public static class Get
{
public static Helpers.EndpointFor.AppEndpointFor Endpoint { get; } =
Helpers.EndpointFor.AppEndpointFor.EndpointCollection;
public static Helpers.PageFor.AppPageFor Page { get; } =
Helpers.PageFor.AppPageFor.PageCollection;
}
Inside AppProgram, bind the endpoint singleton during startup:
protected override EndpointCollection<AppProgram> ConfigureEndpointCollection()
=> Helpers.EndpointFor.AppEndpointFor.EndpointCollection;
To retain an authored page destination, exclude the generated member and provide its replacement in the generated type's partial declaration:
using DRN.Framework.Hosting.Endpoints;
using Example.Hosted;
[assembly: AccessorMember(typeof(AppProgram), "Page.User.Login", Exclude = true)]
namespace Example.Hosted.Helpers.PageFor;
public partial class UserPageFor
{
public string Login { get; init; } = "/User/Login";
}
The exclusion requires a matching page input. Use page identity paths even when @page defines a custom URL route. Additional authored shortcuts that do not replace generated members need no exclusion.
Collection construction no longer scans the host assembly. The startup hook accepts only a collection for the matching program. Leave it unconfigured for hosts without typed controller accessors that need binding. Access runtime endpoint lists through IEndpointAccessor instead of the removed base's static catalog properties. Code that used EndpointSource can construct DrnEndpointSource from IEndpointAccessor.EndpointHelper.EndpointDataSource.
2. Usage in Code
Use the typed accessor members with IDE completion:
// Get the typed endpoint object
ApiEndpoint endpoint = Get.Endpoint.User.Login;
// Generate a URL in the current request, including deployment prefixes.
string url = Url.Endpoint(endpoint);
// Supply route and query values to MVC, which applies routing constraints and encoding.
Guid userId = Guid.NewGuid();
string profileUrl = Url.Endpoint(Get.Endpoint.User.Profile, new { id = userId });
<a asp-page="@Get.Page.User.Login">Log in</a>
The legacy Path(...) overloads remain literal template formatters. Path(id, "{userId:guid}") replaces that exact placeholder, using the GUID's N format. These methods do not apply request prefixes, encode values, select among routes or validate constraints. Prefer Url.Endpoint for links. Static accessors must not retain generated request URLs, users, authorization results or scoped services.
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.
Detailed HTTP exception responses require completed MFA and either the SystemAdmin role or a TestPagesAccess claim set to true, including failures on anonymous endpoints. The same check protects the diagnostic JSON fallback. Both responses set Cache-Control: no-store. Apply [DeveloperExceptionPreview] to preview endpoints and use DeveloperExceptionAccess.AllowsAsync(settings, httpContext) for their navigation links.
Hosts can configure DeveloperExceptionAccess.Policy with additional requirements or authentication schemes. Replacing the named policy preserves the built-in checks on attributed endpoints. Navigation evaluates the policy against the current page request. If policy evaluation fails during exception handling, the viewer receives a redacted response.
The role check accepts the exact claim types configured in AuthenticationClaimConfig.Roles, including its aliases. The role value SystemAdmin and permission claim type TestPagesAccess are case-sensitive.
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 EventIdfields in the owning module'sLoggingnamespace. - 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
ScopeEventandIScopedLog.WithEventinstead of event dictionaries. Standard fields areEventId,EventName,EventOutcome, andEventReason. - 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.
Requests from viewers without diagnostic access and eligible API/HTMX Problem Details skip diagnostic model collection when no post-creation exception filter needs the model. Pre-creation filters run before response selection. Registered post-creation filters receive the populated model in their existing order, unless a pre-filter sets SkipPostCreationFilter. Authorized Development HTML diagnostics and explicit GetExceptionPageModel calls create the model.
Configure application-owned error pages with Hosting's DrnPageOptions:
services.Configure<DrnPageOptions>(options =>
{
options.ServerErrorPage = Get.Page.Root.SomethingWentWrong;
options.NotFoundPage = Get.Page.Root.NotFound;
options.BadRequestPage = Get.Page.Root.BadRequest;
});
DrnPageOptions is in DRN.Framework.Hosting. Error page models are in DRN.Framework.Hosting.Middlewares.ExceptionHandler. Use Razor page names under Pages, without .cshtml. Each error page 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 for browser 5xx exceptions when the viewer lacks diagnostic access, and for bodyless HTML 5xx responses. This includes Development requests. Rendering requires an explicit text/html Accept value and preserves the status, request reference, and deployment prefix. If rendering the configured page fails before the response starts, viewers without diagnostic access receive 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 for browser exceptions mapped to 404 when the viewer lacks diagnostic access. It preserves the status and request reference. API failures use Problem Details JSON. Missing routes pass through the application's authorization and fallback policies before they can return 404.
BadRequestPage uses BadRequestPageModel and follows the same HTML rendering rules for bodyless browser 400 responses and browser exceptions mapped to 400. Direct GET requests return 400. API validation retains its errors and includes the common request reference.
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 DrnPageOptions 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 Foundto303 See Other. For example, a redirect after form submission uses GET for the destination. Use307or308when the destination must preserve the request method. - Secure Caching Default: Dynamic responses that do not set their own
Cache-Controlreceiveno-store, no-cache, must-revalidate. Explicit response caching directives take precedence, while static assets opt into public caching.
Static Asset Compression
DRN does not compress responses at runtime. Compress static assets during the frontend build and deploy the generated files with their Vite manifests. Original assets, Razor HTML and API JSON are served uncompressed on HTTP and HTTPS.
Static files default to one-year public caching. /robots.txt requires cache revalidation by default, with no application configuration needed. Add or customize response headers at startup:
using DRN.Framework.Hosting.DrnProgram;
using Microsoft.Net.Http.Headers;
builder.Services.Configure<DrnStaticFileHeaderOptions>(options =>
{
options.Set(new DrnStaticFileHeaderRule("/downloads/guide.pdf", HeaderNames.ContentDisposition,
"attachment", DrnStaticFileHeaderBehavior.IfMissing));
});
Set adds or updates a rule by path and header name. Override replaces the response header and is the default. IfMissing preserves an existing header. Use Remove("/robots.txt", HeaderNames.CacheControl) to remove the default exception and restore normal static-file caching.
Paths match exactly and case-insensitively, excluding query strings, deployment prefixes, and StaticFileOptions.RequestPath. Wildcards are unsupported. Invalid paths and headers are rejected. Header values are validated at startup against Kestrel's ResponseHeaderEncodingSelector, which defaults to ASCII. Custom encodings remain supported, but unrepresentable values are rejected instead of replaced. Rules apply to public static files and do not change access control.
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. 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;
Related Packages
- DRN.Framework.SharedKernel - Domain primitives and exceptions
- DRN.Framework.Utils - Configuration and DI utilities
- DRN.Framework.EntityFramework - EF Core integration
- DRN.Framework.Testing - Testing utilities
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-19 22:44:23 +0300
Hash: 08d1834aad59fddc366d9d45964489e1c1a6a4a8
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- DRN.Framework.Utils (>= 0.11.0-preview002)
- NetEscapades.AspNetCore.SecurityHeaders (>= 1.3.1)
- NLog.Targets.Network (>= 6.2.2)
- NLog.Web.AspNetCore (>= 6.3.0)
- Swashbuckle.AspNetCore (>= 11.0.1)
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-19 22:44:23 +0300 Hash: 08d1834aad59fddc366d9d45964489e1c1a6a4a8 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.11.0-preview002 | 0 | 11/19/2026 |
| 0.11.0-preview001 | 86 | 11/12/2026 |
| 0.10.1-preview008 | 88 | 11/8/2026 |
| 0.10.1-preview007 | 97 | 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 | 116 | 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 | 125 | 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 |
## Version 0.11.0
### Changed
* **Exception diagnostics**: Buffered request-body capture continues across short reads up to the capture limit. Exception pages capture the request protocol, scheme, and method before larger fields consume the shared budget, and capture the request body before endpoint metadata can exhaust the node budget. They retain captured endpoint metadata rows and indicate when additional entries were omitted.
* **Static-file headers**: Configure exact-path response headers at startup with `DrnStaticFileHeaderOptions`. Rules support replacement, removal, and override or set-if-missing behavior. Static `/robots.txt` responses now require cache revalidation by default. Other static files retain their existing cache lifetime.
* **Swagger configuration**: Swagger UI resolves its default document URL from the configured OpenAPI route, including deployment prefixes. Explicit UI document URLs remain supported.
* **OpenAPI 64-bit integers**: Generated schemas describe both JSON numbers and decimal strings for `long` values, including null for nullable values. Clients can preserve precision when reading large integers.
* **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.
* **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
* **Development exception responses**: Detailed pages and their diagnostic JSON fallback require completed MFA and either `SystemAdmin` or `TestPagesAccess=true`. Both honor stricter host requirements on `DeveloperExceptionAccess.Policy` and send `Cache-Control: no-store`. Authorized pages display unredacted scoped logs and request details within capture limits and `[IgnoreLog]` exclusions. Protect preview endpoints with `[DeveloperExceptionPreview]` and check link visibility with `DeveloperExceptionAccess.AllowsAsync`.
* **Diagnostic IDs**: Replace `DRNHG001` and `DRNHG002` with `DRNHOSTING001` and `DRNHOSTING002` respectively in severity settings and intentional suppressions.
* **Program naming**: Classes deriving directly or indirectly from `DrnProgramBase<TProgram>` must end with the case-sensitive suffix `Program`. The Hosting analyzer reports error `DRNHOSTING002` for other names, including abstract, generic and nested descendants.
* **Typed endpoint collections**: Replace `EndpointCollectionBase<TProgram>` with `EndpointCollectionBase<TProgram, TCollection>` and return `TCollection.EndpointCollection` from the program's `ConfigureEndpointCollection` override. Collections are constructed directly instead of discovered through assembly scanning. Generated roots use the new base and also require the host hook. Use `IEndpointAccessor` for runtime endpoint lists instead of the removed base's static catalog properties. To replace `EndpointSource`, construct `DrnEndpointSource` from the accessor's endpoint helper data source.
* **Target framework**: Requires .NET 11 and ASP.NET Core 11.
* **Swagger UI defaults**: The browser-tab title defaults to the API name and OpenAPI version. Set `Title` or the UI callback's `DocumentTitle` to override it. UI prefixes accept only nonempty ASCII letter, digit, hyphen or underscore segments.
* **OpenAPI documents**: Swagger now serves OpenAPI 3.2 by default. Hosts with tooling that requires 3.1 can set `OpenApiVersion` to `OpenApiSpecVersion.OpenApi3_1` in `ConfigureSwaggerEndpointOptionsAction`.
* **Swagger UI authorization**: Without a named `AuthorizationPolicy`, Swagger UI now uses the application's fallback authorization policy. Anonymous catch-all routes no longer grant access to Swagger UI.
* **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
* **Accessor route conventions**: Generated controller accessors infer legacy route metadata from a single distinct standard controller route template, including inherited declarations. Explicit `RouteTemplate` overrides, including empty values, take precedence. Controller overrides can omit the accessor path to retain the namespace convention. Multiple templates and custom route providers retain empty metadata. Runtime routing is unchanged.
* **Hosted accessor generation**: SDK Web hosts automatically receive PageFor and EndpointFor collections for local public, concrete, top-level, non-generic programs whose `DrnProgramBase<TProgram>` argument is the program itself. Root names remove the `Program` suffix, with `Program` alone using `App`. Generated types use the program namespace plus `Helpers.PageFor` or `Helpers.EndpointFor`, with compiler-owned sources under matching Helpers hint folders. Both roots are generated, with an empty page collection when no Razor `@page` inputs exist. Hosting distributes the net10.0 generator transitively through package build assets and shared project build targets while applications remain on net11.0. Non-Web projects do not generate helpers. Controller, group and member aliases and partial customization preserve existing access paths. Typed singleton access returns initialized properties directly without per-access lookups. Inherited Source-Known actions and `[NonAction]` exclusions are supported. Runtime routing remains authoritative, and parameter/constraint generation remains deferred.
* **Source-Known Controllers**: Added `SourceKnownController` for combined reads and writes, plus `SourceKnownReadOnlyController` and `SourceKnownWriteOnlyController` for restricted endpoint sets. Reads provide bounded DTO lookup and pagination. DRNAUTHORIZATION001 requires explicit named authorization policies on exposed actions and rejects anonymous access. Writes require application mapping. API actions have no mandatory antiforgery filter; configure explicit bearer-only policies for SPA clients, or add antiforgery validation when enabling cookie authentication. Keep resource-specific authorization in application code. Override exposed actions with `[NonAction]` to remove their endpoints.
* **Swagger UI options**: Set `AddSwaggerUI = false` to retain the OpenAPI document without the UI. Set `DrnPageOptions.FaviconUrl` to supply a local browser-tab icon that respects deployment prefixes.
* **Pagination schemas**: Swagger documents optional page size and cursor fields for `[FromQuery] PaginationRequest` and `PaginationResultInfo` and omits calculated fields while preserving continuation totals. Explicit query prefixes are preserved. JSON body schemas preserve their required fields and validation. Shared operation guidance describes query/body placement and pagination responses while preserving application descriptions. Field descriptions distinguish returned-page IDs from the previous-page cursor and explain total-count metadata.
* **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**: `DrnPageOptions` in `DRN.Framework.Hosting` configures 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.
* **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)` and `LinkGenerator.GetUriByEndpoint(HttpContext, endpoint, values)` for request-aware MVC paths and absolute URIs. They preserve deployment prefixes, use effective MVC action names and destination areas, and report missing/ambiguous metadata and generation failures. Addresses shared by different CLR actions are rejected; use distinct MVC names/areas or explicitly named routing. Identity confirmation links use this metadata-aware generation. 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
* **Endpoint accessors**: `Path(Guid, template)` now honors the supplied placeholder. Missing endpoint bindings report discovery guidance. Multiple route selectors sharing an MVC action descriptor no longer fail catalog initialization; the endpoint accessor retains every route.
* **Swagger security**: Anonymous operations no longer advertise the default bearer authentication requirement.
* **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**