Moclawr.Host 2.1.0

dotnet add package Moclawr.Host --version 2.1.0
                    
NuGet\Install-Package Moclawr.Host -Version 2.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Moclawr.Host" Version="2.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Moclawr.Host" Version="2.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Moclawr.Host" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Moclawr.Host --version 2.1.0
                    
#r "nuget: Moclawr.Host, 2.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Moclawr.Host&version=2.1.0
                    
Install Moclawr.Host as a Cake Addin
#tool nuget:?package=Moclawr.Host&version=2.1.0
                    
Install Moclawr.Host as a Cake Tool

Moclawr.Host

NuGet

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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.1.0 132 5/28/2025
2.0.0 63 5/24/2025
1.0.3 61 5/24/2025
1.0.2 137 5/22/2025
1.0.1 139 5/21/2025
1.0.0 209 5/15/2025

Added improved XML documentation and bug fixes.