This playground demonstrates how to use custom DelegatingHandler in ASP.NET Core Minimal APIs (.NET 10, C# 14). It showcases building a pipeline of HTTP message handlers for cross-cutting concerns like logging, authentication, error handling, and header propagation.
- Custom DelegatingHandlers: Create and chain multiple
DelegatingHandlerclasses to intercept and modify outgoing HTTP requests and responses, enabling features like structured logging with ILogger, API key injection, performance tracking, and comprehensive error handling.
- Refit: Generate strongly-typed HTTP clients from REST API interfaces for clean, type-safe API calls.
- Header Propagation Middleware: Automatically propagate specified headers (e.g.,
X-TraceId) from incoming requests to outgoing HTTP requests using ASP.NET Core's built-in middleware. - Health Checks: Built-in
/healthendpoint for monitoring application status. - Comprehensive Error Handling: Proper exception handling with detailed error responses and logging.
- Structured Logging: Uses ASP.NET Core's ILogger for production-ready logging with performance metrics.
- Inherit from
DelegatingHandlerto create handlers for specific concerns (e.g., structured logging with ILogger, adding authentication, performance tracking). - Chain handlers in the desired order using
.AddHttpMessageHandler<T>()on theHttpClientbuilder. Note that built-in handlers likeAddHeaderPropagation()should be added before custom handlers to ensure proper execution order. - Handlers execute in the order they are added, allowing for modular and reusable HTTP pipeline logic.
- Best Practices:
- Use dependency injection for
ILoggerandIConfiguration. - Validate required configuration (e.g., API keys) and throw meaningful exceptions.
- Track request duration for performance monitoring.
- Avoid logging sensitive data (e.g., Authorization headers).
- Use dependency injection for
- Define an interface for your API (see
IWeatherApi). - Register with
AddRefitClientin DI for automatic client generation. - Use in endpoints via dependency injection for seamless API integration.
- Configure which headers to propagate in
Program.csusingAddHeaderPropagation. - Attach to
HttpClientinstances with.AddHeaderPropagation(). - Use
UseHeaderPropagation()in the middleware pipeline to enable propagation from incoming requests.
/weather/{city}: Retrieves current weather for a city using Refit, with handlers chained in this order: Header Propagation (adds propagated headers), Logging (logs request details including headers and performance metrics), and API Key (injects and validates the API key as a query parameter). Includes comprehensive error handling with proper HTTP status codes and structured logging./health: Health check endpoint for monitoring application status.
- Create an account at WeatherAPI to obtain an API key.
- Set the API key in user-secrets:
dotnet user-secrets set "WeatherApi:Key" "your-api-key"
- Clone the repo.
- Set your weather API key using user-secrets as described above.
- Run the project (
dotnet run). - Explore endpoints with Swagger UI (
/swagger) or use the health check endpoint (/health).
- Missing API Key Error: If you see an error about missing API key, ensure you've set it using:
dotnet user-secrets set "WeatherApi:Key" "your-api-key" - 404 Not Found: The city name may be invalid or not found in the WeatherAPI database. Try common city names like "London" or "New York".
- Health Check: Visit
/healthto verify the application is running correctly.
- ✅ Structured logging with ILogger
- ✅ Comprehensive error handling with proper HTTP status codes
- ✅ Request/Response validation
- ✅ Configuration validation (API key required)
- ✅ Performance tracking (request duration)
- ✅ Health checks endpoint
- ✅ Security best practices (no sensitive data in logs)
- ✅ OpenAPI/Swagger documentation
This project is licensed under the MIT License - see the LICENSE file for details.
.NET 10 / C# 14 | Modern ASP.NET Core | Educational Playground