DRN.Framework.Hosting
0.7.0-preview059
Prefix Reserved
See the version list below for details.
dotnet add package DRN.Framework.Hosting --version 0.7.0-preview059
NuGet\Install-Package DRN.Framework.Hosting -Version 0.7.0-preview059
<PackageReference Include="DRN.Framework.Hosting" Version="0.7.0-preview059" />
<PackageVersion Include="DRN.Framework.Hosting" Version="0.7.0-preview059" />
<PackageReference Include="DRN.Framework.Hosting" />
paket add DRN.Framework.Hosting --version 0.7.0-preview059
#r "nuget: DRN.Framework.Hosting, 0.7.0-preview059"
#:package DRN.Framework.Hosting@0.7.0-preview059
#addin nuget:?package=DRN.Framework.Hosting&version=0.7.0-preview059&prerelease
#tool nuget:?package=DRN.Framework.Hosting&version=0.7.0-preview059&prerelease
DRN.Framework.Hosting
Application shell for DRN web applications with security-first design, structured lifecycle, and type-safe routing.
TL;DR
- Secure by Default - MFA enforced (Fail-Closed), strict CSP with Nonces, HSTS automatic
- Opinionated Startup -
DrnProgramBasewith 20+ overrideable lifecycle hooks - Type-Safe Routing - Typed
EndpointandPageaccessors replace magic strings - Zero-Config Infrastructure - Auto-provision Postgres/RabbitMQ in Debug mode
- Frontend Integration - TagHelpers for Vite manifest, CSRF for HTMX, secure assets
Table of Contents
- QuickStart: Beginner
- QuickStart: Advanced
- Directory Structure
- Lifecycle & Execution Flow
- DrnProgramBase Deep Dive
- Configuration
- Security Features
- Endpoint Management
- Razor TagHelpers
- Local Development
- Global Usings
QuickStart: Beginner
All DRN web apps inherit from DrnProgramBase<TProgram> to inherit the lifecycle hooks and default behaviors.
using DRN.Framework.Hosting.DrnProgram;
using DRN.Framework.Hosting.HealthCheck;
namespace Sample.Hosted;
public class Program : DrnProgramBase<Program>, IDrnProgram
{
// Entry Point (Runs the opinionated bootstrapping)
public static async Task Main(string[] args) => await RunAsync(args);
// [Required] Service Registration Hook
protected override Task AddServicesAsync(WebApplicationBuilder builder, IAppSettings appSettings, IScopedLog scopedLog)
{
builder.Services.AddSampleInfraServices(appSettings);
builder.Services.AddSampleApplicationServices();
return Task.CompletedTask;
}
}
// Immediate API endpoint for testing and health checks (Inherits [AllowAnonymous] and Get())
[Route("[controller]")]
public class WeatherForecastController : WeatherForecastControllerBase;
QuickStart: Advanced
Test your application using DRN.Framework.Testing to spin up the full pipeline including databases.
[Theory, DataInline]
public async Task WeatherForecast_Should_Return_Data(DrnTestContext context, ITestOutputHelper outputHelper)
{
// Arrange
var client = await context.ApplicationContext.CreateClientAsync<Program>(outputHelper);
// Act
var response = await client.GetAsync("WeatherForecast");
// Assert
response.StatusCode.Should().Be(HttpStatusCode.OK);
var data = await response.Content.ReadFromJsonAsync<IEnumerable<WeatherForecast>>();
data.Should().NotBeEmpty();
}
Directory Structure
DRN.Framework.Hosting/
├── DrnProgram/ # DrnProgramBase, options, actions, conventions
├── Endpoints/ # EndpointCollectionBase, PageForBase, type-safe accessors
├── Auth/ # Policies, MFA configuration, requirements
├── Consent/ # GDPR cookie consent management
├── Identity/ # Identity integration and scoped user middleware
├── Middlewares/ # HttpScopeLogger, exception handling, security middlewares
├── TagHelpers/ # Razor TagHelpers (Vite, Nonce, CSRF, Auth-Only)
├── Areas/ # Framework-provided Razor Pages (e.g., Error pages)
├── wwwroot/ # Framework style and script assets
Lifecycle & Execution Flow
DrnProgramBase orchestrates the application startup to ensure security headers, logging scopes, and validation logic run in the correct order. Use DrnProgramActions to intercept these phases without cluttering your main Program class.
graph TD
Start["RunAsync()"] --> CAB["CreateApplicationBuilder()"]
subgraph "1. Builder Phase (Services & Config)"
CAB --> CSO["ConfigureSwaggerOptions()"]
CAB --> CDSH["ConfigureDefaultSecurityHeaders()"]
CDSH --> CDCSP["ConfigureDefaultCsp()"]
CAB --> CSHPB["ConfigureSecurityHeaderPolicyBuilder()"]
CAB --> CCP["ConfigureCookiePolicy()"]
CAB --> CSFO["ConfigureStaticFileOptions()"]
CAB --> CFHO["ConfigureForwardedHeadersOptions()"]
CAB --> CMVCB["ConfigureMvcBuilder()"]
CAB --> CAO["ConfigureAuthorizationOptions()"]
CAB --> ASA["AddServicesAsync()"]
ASA --> ABC["ApplicationBuilderCreatedAsync (Action)"]
end
ABC --> Build["builder.Build()"]
subgraph "2. Application Phase (Middleware)"
Build --> CA["ConfigureApplication()"]
CA --> CAPS["ConfigureApplicationPipelineStart() (HSTS/Headers)"]
CAPS --> CAPR["ConfigureApplicationPreScopeStart() (Static Files)"]
CAPR --> HSM["HttpScopeMiddleware (TraceId/Logging)"]
HSM --> CPSS["ConfigureApplicationPostScopeStart()"]
CPSS --> UR["UseRouting()"]
UR --> CAPREA["ConfigureApplicationPreAuthentication()"]
CAPREA --> AUTH["UseAuthentication()"]
AUTH --> SUM["ScopedUserMiddleware"]
SUM --> CAPOSTA["ConfigureApplicationPostAuthentication()"]
CAPOSTA --> MFAE["MfaExemptionMiddleware"]
CAPOSTA --> MFAR["MfaRedirectionMiddleware"]
MFAE --> UA["UseAuthorization()"]
MFAR --> UA
UA --> CPSTAZ["ConfigureApplicationPostAuthorization() (Swagger UI)"]
CPSTAZ --> MAE["MapApplicationEndpoints()"]
end
MAE --> ABA["ApplicationBuiltAsync (Action)"]
ABA --> VE["ValidateEndpoints()"]
VE --> VSA["ValidateServicesAsync()"]
VSA --> AVA["ApplicationValidatedAsync (Action)"]
AVA --> Run["application.RunAsync()"]
DrnProgramBase Deep Dive
This section details the hooks available to customize your application's lifecycle. DrnProgramBase follows a "Hook Method" pattern: the base class defines the workflow, and you override virtual methods to inject logic.
1. Configuration Hooks (Builder Phase)
These hooks run while the WebApplicationBuilder is active, allowing you to configure the DI container and system options.
| Category | Method | Purpose |
|---|---|---|
| OpenAPI | ConfigureSwaggerOptions |
Customize Swagger UI title, version, and visibility settings. |
| MVC | ConfigureMvcBuilder |
Add ApplicationParts, custom formatters, or enable Razor Runtime Compilation. |
| MVC | ConfigureMvcOptions |
Add global filters, conventions, or customize model binding. |
| Auth | ConfigureAuthorizationOptions |
Define security policies. Note: Sets MFA as the default/fallback by default. |
| Security | ConfigureDefaultSecurityHeaders |
Define global headers (HSTS, CSP, FrameOptions). |
| Security | ConfigureDefaultCsp |
Customize CSP directives (Script, Image, Style sources). |
| 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 | ConfigureSecurityStampValidatorOptions |
Customize security stamp validation and claim preservation. |
| Infras. | ConfigureStaticFileOptions |
Customize caching (default: 1 year) and HTTPS compression. |
| 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 |
Configure response caching middleware settings. |
| Global | AddServicesAsync |
[Required] The primary place to register your application services. |
2. Pipeline Hooks (Application Phase)
These hooks define the request processing middleware sequence.
| Order | Hook | Typical Usage |
|---|---|---|
| 1 | ConfigureApplicationPipelineStart |
UseForwardedHeaders, UseHostFiltering, UseCookiePolicy. |
| 2 | ConfigureApplicationPreScopeStart |
UseStaticFiles. Runs before request logging/trace ID is established. |
| 3 | ConfigureApplicationPostScopeStart |
Add middleware that needs access to IScopedLog but runs before routing. |
| 4 | ConfigureApplicationPreAuthentication |
UseRequestLocalization. Runs before the user identity is resolved. |
| 5 | ConfigureApplicationPostAuthentication |
MfaRedirectionMiddleware, MfaExemptionMiddleware. Logic that runs after the user is known but before access checks. |
| 6 | ConfigureApplicationPostAuthorization |
UseSwaggerUI. Runs after access is granted but before the final endpoint. |
| 7 | MapApplicationEndpoints |
MapControllers, MapRazorPages, MapHubs. |
3. Verification Hooks
| Hook | Purpose |
|---|---|
ValidateEndpoints |
Ensures all type-safe endpoint accessors match actual mapped routes. |
ValidateServicesAsync |
Scans the container for [Attribute] based registrations and ensures they are resolvable. |
4. MFA Configuration Hooks
| Hook | Purpose |
|---|---|
ConfigureMFARedirection |
Configure MFA setup and login redirection URLs. Returns null to disable. |
ConfigureMFAExemption |
Configure authentication schemes exempt from MFA requirements. Returns null to disable. |
5. Internal Wiring (Automatic)
- Service Validation: Calls
ValidateServicesAsyncto scan[Attribute]-registered services and ensure they are resolvable at startup. - Secure JSON: Enforces
HtmlSafeWebJsonDefaultsto prevent XSS via JSON serialization. - Endpoint Accessor: Registers
IEndpointAccessorfor typed access toEndpointCollectionBase.
6. Properties
| Property | Default | Purpose |
|---|---|---|
AppBuilderType |
DrnDefaults |
Controls builder creation. Use Slim for minimal APIs. |
DrnProgramSwaggerOptions |
(Object) | Toggles Swagger generation. Defaults to IsDevEnvironment. |
NLogOptions |
(Object) | Controls NLog bootstrapping (e.g., replace logger factory). |
Configuration
Configuration Precedence: Environment > Secrets > AppSettings.
Always use User Secrets for local connection strings to avoid committing credentials.
Layering
appsettings.jsonappsettings.{Environment}.json- User Secrets (Development only)
- Environment Variables (
ASPNETCORE_,DOTNET_) - Mounted Directories (e.g.
/app/config) - Command Line Arguments
Reference Configurations
NLog (Logging)
Standard configuration for Console and Graylog output.
{
"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" }
}
}
}
Security Features
DRN Hosting enforces a "Fail-Closed" security model. If you forget to configure something, it remains locked.
1. MFA Enforcement (Fail-Closed)
The framework sets the FallbackPolicy for the entire application to require a Multi-Factor Authentication session.
- Result: Any new controller or page you add is secure by default.
- Opt-Out: Use
[AllowAnonymous]or[Authorize(Policy = AuthPolicy.MfaExempt)]for single-factor pages like Login or MFA Setup.
2. MFA Configuration
Configure MFA behavior by overriding these hooks in your DrnProgramBase implementation:
// Configure MFA redirection URLs
protected override MfaRedirectionConfig ConfigureMFARedirection()
=> new(
mfaSetupUrl: Get.Page.User.EnableAuthenticator,
mfaLoginUrl: Get.Page.User.LoginWith2Fa,
loginUrl: Get.Page.User.Login,
logoutUrl: Get.Page.User.Logout,
allowedUrls: Get.Page.All
);
// Exempt specific authentication schemes from MFA
protected override MfaExemptionConfig ConfigureMFAExemption()
=> new(exemptSchemes: ["ApiKey", "Certificate"]);
3. Content Security Policy (Nonce-based)
DRN automatically generates a unique cryptographic nonce for every request.
- Automatic Protection: Scripts and styles without a matching nonce are blocked by the browser, stopping most XSS attacks.
- Usage: Use the
NonceTagHelper(see below) to automatically inject these nonces.
4. Transparent Security Headers
Standard security headers are injected into every response:
- HSTS: Strict-Transport-Security (2 years, includes subdomains).
- FrameOptions:
DENY(prevents clickjacking). - ContentTypeOptions:
nosniff. - ReferrerPolicy:
strict-origin-when-cross-origin.
5. GDPR & Cookie Security
Cookies are configured with SameSite=Strict and HttpOnly by default to mitigate CSRF and session hijacking. The ConsentCookie system ensures compliance with privacy regulations.
Endpoint Management
Avoid "magic strings" in your code. DRN provides a type-safe way to reference routes that is verified at startup.
1. Define Your Accessors
Create a class inheriting from EndpointCollectionBase<Program> or PageCollectionBase<Program>.
public class Get : EndpointCollectionBase<Program>
{
public static UserEndpoints User { get; } = new();
}
public class UserEndpoints : ControllerForBase<UserController>
{
// Template: /Api/User/[controller]/[action]
public UserEndpoints() : base("/Api/User/[controller]") { }
// Properties matching Controller Action names
public ApiEndpoint Login { get; private set; } = null!;
public ApiEndpoint Profile { get; private set; } = null!;
}
2. Usage in Code
Resolve routes at compile-time with full IDE support (intellisense).
// Get the typed endpoint object
ApiEndpoint endpoint = Get.User.Login;
// Generate the path string
string url = endpoint.Path(); // "/Api/User/User/Login"
// Generate path with route parameters
string profileUrl = Get.User.ProfileDetail.Path(new() { ["id"] = userId.ToString() });
Razor TagHelpers
| TagHelper | Target | Purpose |
|---|---|---|
ViteScriptTagHelper |
<script src="buildwww/..."> |
Resolves Vite manifest entries and adds subresource integrity. |
NonceTagHelper |
<script>, <style> |
Automatically injects the request-specific CSP nonce. |
CsrfTokenTagHelper |
hx-post, hx-put |
Automatically adds RequestVerificationToken to HTMX headers. |
AuthorizedOnlyTagHelper |
*[authorized-only] |
Renders the element only if the user has an active MFA session. |
PageAnchorTagHelper |
<a asp-page="..."> |
Automatically adds active CSS class if the link matches current page. |
Example: Secure Script Loading
<script src="buildwww/app/main.ts" crossorigin="anonymous"></script>
<script src="/app/main.abc123.js"
integrity="sha256-xyz..."
nonce="random_nonce_here"
crossorigin="anonymous"></script>
Local Development Infrastructure
Use DRN.Framework.Testing to provision infrastructure (Postgres, RabbitMQ) during local development without manual Docker management.
1. Add Conditional Reference
Add the following to your .csproj file to ensure the testing library (and its heavy dependencies like Testcontainers) is only included during development.
<ItemGroup Condition="'$(Configuration)' == 'Debug'">
<ProjectReference Include="..\DRN.Framework.Testing\DRN.Framework.Testing.csproj" />
</ItemGroup>
2. Configure Startup Actions
Implement DrnProgramActions to trigger the auto-provisioning.
#if DEBUG
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
}
};
// Auto-starts containers if not running and updates AppSettings
await builder.LaunchExternalDependenciesAsync(scopedLog, appSettings, options);
}
}
#endif
Global Usings
Standard 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;
Semper Progressivus: Always Progressive
Commit Info
Author: Duran Serkan KILIÇ
Date: 2026-01-26 21:12:39 +0300
Hash: 858b6f431aa962dcd742ffa77fa3a94322c3754e
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- DRN.Framework.Utils (>= 0.7.0-preview059)
- Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation (>= 10.0.2)
- NetEscapades.AspNetCore.SecurityHeaders (>= 1.3.1)
- NLog.Targets.Network (>= 6.0.3)
- NLog.Web.AspNetCore (>= 6.1.0)
- Swashbuckle.AspNetCore (>= 10.1.0)
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 KILIÇ Date: 2026-03-14 17:32:18 +0300 Hash: 9ef739ee5aaa5d5507ba19619770bf86581ed4e4 |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.8.0 | 32 | 3/14/2026 |
| 0.7.0 | 86 | 3/8/2026 |
| 0.7.0-preview067 | 86 | 3/7/2026 |
| 0.7.0-preview066 | 98 | 2/28/2026 |
| 0.7.0-preview065 | 94 | 2/25/2026 |
| 0.7.0-preview064 | 96 | 2/22/2026 |
| 0.7.0-preview063 | 95 | 2/21/2026 |
| 0.7.0-preview062 | 93 | 2/11/2026 |
| 0.7.0-preview061 | 118 | 2/7/2026 |
| 0.7.0-preview060 | 100 | 1/28/2026 |
| 0.7.0-preview059 | 113 | 1/26/2026 |
| 0.7.0-preview058 | 108 | 1/25/2026 |
| 0.7.0-preview057 | 101 | 1/25/2026 |
| 0.7.0-preview056 | 107 | 1/10/2026 |
| 0.7.0-preview055 | 285 | 12/16/2025 |
| 0.7.0-preview054 | 199 | 12/13/2025 |
| 0.7.0-preview053 | 139 | 12/12/2025 |
| 0.7.0-preview052 | 457 | 12/9/2025 |
| 0.7.0-preview051 | 318 | 12/7/2025 |
| 0.7.0-preview050 | 229 | 12/7/2025 |
Not every version includes changes, features or bug fixes. This project can increment version to keep consistency with other DRN.Framework projects.
## Version 0.7.0
My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals.
### New Features
* IdentityControllerBase classes added which are controller version of Identity Api endpoints.
* DrnProgramBase
* ConfigureSecurityHeaders virtual method added.
* ConfigureApplicationPreScopeStart will add security headers configured by ConfigureSecurityHeaders
## Version 0.6.0
My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals. This release is dedicated to the memory of Mustafa Kemal Atatürk, founder of the Republic of Türkiye, and to his vision for a modern, enlightened, democratic nation. In his eternal rest, he continues to guide us through his ideals of freedom, progress, and national sovereignty.
### New Features
* DrnProgramBase
* MvcBuilder configuration separated into virtual method
* RazorRuntimeCompilation support added
* Exception is no longer swallowed by DrnProgramBase to fail integration tests gracefully
* Multifactor Authentication
* Mfa detail added to scopedlog with ScopedUserMiddleware
* Mfa and Mfa exempt policies added with AuthPolicy helper class
* DrnProgramBase.ConfigureAuthorizationOptions enforces Mfa by default
* MfaExempt policy can be used with Authorize attribute to bypass mfa
* ConfigureMFARedirection and ConfigureMFAExemption virtual methods added to DrnProgramBase
* PageCollectionBase and EndpointCollectionBase classes added to manage page and endpoint references
### Breaking Changes
* DrnProgramBase refactored
* Static properties removed to improve application stability during integration tests
* New overridable virtual methods added to improve configurability
* Overridable virtual method parameters changed to accept instance parameters since static properties does not exist anymore.
## Version 0.5.0
My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals. This release is dedicated to August 30 Victory Day, a day that marks the decisive victory achieved by the Turkish people against imperialism during the Turkish War of Independence, leading to the establishment of the Republic of Türkiye.
### New Features
* ScopedUserMiddleware
* sets IScopedUser with current user belongs to the request scope
* updates IScopedLog with UserId and UserAuthenticated info
* HttpScopeHandler
* Initializes ScopeContext with TraceId, IScopedLog and IScopedUser
* DrnException handling as default application exception handling
* DrnExceptions can be used to short circuit the processing pipeline
* FlurlHttpException handling as default gateway exception handling
* In Development environment - HttpResponse returns ScopedLog as developer exception result
* l5d-client-id is added to scoped log by default
* HttpRequestLogger
* Request and response logs improvements
* DrnProgramBase
* HostOptions become configurable with Configuration.GetSection("HostOptions")
* overrideable ConfigureSwaggerOptions
* Added swagger support by default in development environment
### Breaking Changes
* DrnProgramBase
* DrnProgramOptions - Removed
## Version 0.4.0
My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals. This release is dedicated to 19 May Commemoration of Atatürk, Youth and Sports Day.
### Breaking Changes
* HttpScopeLogger is renamed as HttpScopeHandler
### New Features
* EndpointsApiExplorer - added to service collection by DrnProgramBase to support OpenAPI Specification
* NexusClient - added for initial service discovery and remote configuration management development
* DrnProgramBase has new overridable configuration methods
* ConfigureApplicationPreScopeStart
* ConfigureApplicationPostScopeStart
* MapApplicationEndpoints
## Version 0.3.0
My family celebrates the enduring legacy of Mustafa Kemal Atatürk's enlightenment ideals. This release is dedicated to 23 April National Sovereignty and Children's Day.
### New Features
* DrnProgramBase and IDrnProgram - added to minimize development efforts with sensible defaults
* HttpScopeLogger and HttpRequestLogger middlewares - added to support structured logging
---
**Semper Progressivus: Always Progressive**
## Commit Info
Author: Duran Serkan KILIÇ
Date: 2026-01-26 21:12:39 +0300
Hash: 858b6f431aa962dcd742ffa77fa3a94322c3754e