Moclawr.Host
2.1.0
dotnet add package Moclawr.Host --version 2.1.0
NuGet\Install-Package Moclawr.Host -Version 2.1.0
<PackageReference Include="Moclawr.Host" Version="2.1.0" />
<PackageVersion Include="Moclawr.Host" Version="2.1.0" />
<PackageReference Include="Moclawr.Host" />
paket add Moclawr.Host --version 2.1.0
#r "nuget: Moclawr.Host, 2.1.0"
#addin nuget:?package=Moclawr.Host&version=2.1.0
#tool nuget:?package=Moclawr.Host&version=2.1.0
Moclawr.Host
Overview
Moclawr.Host provides essential infrastructure for building robust and maintainable ASP.NET Core applications. It includes global exception handling, health checks, logging with Serilog, and various middleware components to streamline application setup and improve error handling and monitoring capabilities.
Features
- Global Exception Handling: Centralized error handling with custom exception handlers
- Health Checks: Database and service health monitoring
- Structured Logging: Pre-configured Serilog integration with multiple sinks (Console, File, Elasticsearch)
- APM Integration: Elastic APM for application performance monitoring
- CORS Configuration: Simplified cross-origin resource sharing setup
- Custom Middleware: Pre-built middleware for common application needs
- Security Headers: Configurable security headers for web applications
- Authorization Attributes: Custom authorization attributes for securing endpoints
Installation
Install the package via NuGet Package Manager:
dotnet add package Moclawr.Host
Usage
Setting Up Global Exception Handling
In your Program.cs
:
using Host;
// Add global exception handling
builder.Services.AddGlobalExceptionHandling("MyApplication");
// Configure the application
var app = builder.Build();
// Use global exception handling middleware
app.UseGlobalExceptionHandling();
Configuring Serilog
// Add Serilog for structured logging
builder.AddSerilog(builder.Configuration, "MyApplication");
Configuration in appsettings.json:
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "Logs/log-.json",
"rollingInterval": "Hour",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
}
],
"Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"]
}
}
Adding Health Checks
// Add health checks for database and external services
builder.Services.AddHealthChecks(builder.Configuration);
// In the app configuration section
app.MapHealthChecks();
Setting Up CORS
// Add CORS services
builder.Services.AddCorsServices(builder.Configuration);
// In the app configuration section
app.UseCors("DefaultPolicy");
Configuration in appsettings.json:
{
"Cors": {
"AllowedOrigins": ["https://example.com"],
"AllowedMethods": ["GET", "POST", "PUT", "DELETE"],
"AllowedHeaders": ["Content-Type", "Authorization"],
"AllowCredentials": true
}
}
Adding Database Health Checks
// Add database context health check
builder.Services.AddDbContextHealthCheck<ApplicationDbContext>("Database");
Using Elastic APM
// Configure Elastic APM
builder.Services.AddElasticApm(builder.Configuration);
// In the app configuration section
app.UseAllElasticApm(builder.Configuration);
Configuration in appsettings.json:
{
"ElasticApm": {
"ServerUrl": "http://localhost:8200",
"ServiceName": "MyApplication",
"Environment": "Development"
}
}
Using Custom Exception Handlers
You can create custom exception handlers by implementing the IExceptionHandler
interface:
[HandlerFor(typeof(MyCustomException))]
public class MyCustomExceptionHandler : IExceptionHandler
{
public async Task HandleException(HttpContext context, Exception exception, ILogger logger)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
context.Response.ContentType = "application/json";
var response = new
{
Status = 400,
Message = "A custom error occurred",
Details = exception.Message
};
await context.Response.WriteAsJsonAsync(response);
}
}
Integration with Other Moclawr Packages
This package works seamlessly with other packages in the Moclawr ecosystem:
- Moclawr.Core: Provides core utilities and extensions
- Moclawr.Shared: Contains shared models, interfaces, and settings
- Moclawr.Domain: Domain entities and business logic primitives
- Moclawr.EfCore: Integrates with Entity Framework Core for database health checks
- Moclawr.MongoDb: Supports MongoDB health monitoring
- Moclawr.MinimalAPI: Works together for complete API solutions with exception handling
- Moclawr.Services.Caching: Integrates with caching health checks
- Moclawr.Services.External: External service health monitoring
Requirements
- .NET 9.0 or higher
- Serilog.AspNetCore 9.0.0 or higher
- AspNetCore.HealthChecks.UI.Client 9.0.0 or higher
- Microsoft.EntityFrameworkCore 9.0.4 or higher (for database health checks)
License
This package is licensed under the MIT License.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. 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. |
-
net9.0
- AspNetCore.HealthChecks.UI.Client (>= 9.0.0)
- AspNetCore.HealthChecks.UI.Core (>= 9.0.0)
- AspNetCore.HealthChecks.Uris (>= 9.0.0)
- DotNetCore.CAP.Pulsar (>= 8.3.4)
- Elastic.Apm.NetCoreAll (>= 1.23.0)
- Microsoft.EntityFrameworkCore (>= 9.0.4)
- Moclawr.Core (>= 2.1.0)
- Serilog.AspNetCore (>= 9.0.0)
- Serilog.Settings.Configuration (>= 9.0.0)
- Serilog.Sinks.Async (>= 2.1.0)
- Serilog.Sinks.Console (>= 6.0.0)
- Serilog.Sinks.Elasticsearch (>= 9.0.3)
- Serilog.Sinks.File (>= 7.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Added improved XML documentation and bug fixes.