ASP.NET Core Middleware for API Audit Logging

October 19, 2025 · 7 min

In modern application development, especially with APIs, knowing what’s happening under the hood isn’t just a “nice-to-have,” it’s a necessity. Audit logging provides a detailed record of every significant action, which is invaluable for security, compliance (like GDPR or HIPAA), and debugging complex issues.

While you could add logging calls in every controller action, that approach is repetitive and error-prone. A much cleaner, more powerful solution is to use ASP.NET Core’s middleware. In this post, we’ll build a piece of custom middleware from scratch to create a robust audit logging system for any API.

What is Middleware, Really?

Think of the ASP.NET Core request pipeline as an assembly line. When an HTTP request comes in, it passes through a series of components, or “middleware,” before it reaches your API controller. Each piece of middleware has a chance to inspect the request, modify it, or even short-circuit it. After the controller generates a response, it travels back down the same line.

This structure makes middleware the perfect place for cross-cutting concerns like authentication, caching, exception handling, and, of course, logging.

Designing Our Audit Logging Middleware

Before writing code, let’s define what information we want to capture for each API call. A good audit log should be comprehensive.

Key Data Points to Log:

  • Request Info: HTTP Method, Path, Query String, Headers, and the Request Body. …
...

Read more

Consistent API Errors with ProblemDetails in ASP.NET Core

October 18, 2025 · 6 min

In the world of API development, consistency is king. One of the most common areas where consistency breaks down is error handling. Different endpoints might return different JSON structures for a 404 Not Found versus a 500 Internal Server Error, forcing API consumers to write complex, brittle parsing logic.

ASP.NET Core provides a clean, built-in solution to this problem: the ProblemDetails middleware. By adopting this standard, you can ensure all your API’s error responses have a predictable, machine-readable shape.

What is Problem Details?

ProblemDetails is a specification defined in RFC 7807 that establishes a standard format for returning error information from an HTTP API. It’s essentially a contract for what an error response should look like.

A standard ProblemDetails object includes these key fields:

  • type: A URI that identifies the problem type. This can link to documentation explaining the error.
  • title: A short, human-readable summary of the problem.
  • status: The HTTP status code generated by the server for this occurrence of the problem.
  • detail: A human-readable explanation specific to this occurrence of the problem.
  • instance: A URI that identifies the specific occurrence of the problem.

Here’s an example of what a ProblemDetails response looks like in JSON:

{
  "type": "[https://tools.ietf.org/html/rfc7231#section-6.5.4](https://tools.ietf.org/html/rfc7231#section-6.5.4)",
  "title": "Not Found", …
...

Read more

Debug Multi-Tenant ASP.NET APIs with Custom Middleware

October 17, 2025 · 7 min

Multi-tenant architecture is a powerful way to serve multiple customers from a single, shared application instance. It’s efficient and scalable, but it introduces a significant challenge: when a bug occurs for just one tenant, how do you debug it without disrupting everyone else? Reproducing the issue can be a nightmare of sifting through logs and guessing at tenant-specific configurations.

This is where ASP.NET Core’s middleware pipeline becomes your secret weapon. By creating a small, targeted piece of custom middleware, you can build a powerful debugging toolkit that provides deep visibility into tenant-specific requests on demand. In this post, we’ll walk through how to build a middleware component that helps you zero in on those elusive, tenant-specific bugs.

The Unique Challenge of Debugging Multi-Tenant APIs

In a standard single-tenant application, if a bug exists, it usually affects all users in the same way. In a multi-tenant world, the landscape is far more complex:

  • Configuration Differences: Tenant A might have a feature flag enabled that Tenant B doesn’t.
  • Data Isolation: The exact data being processed for Tenant A could trigger an edge case that Tenant B’s data never will.
  • Custom Workflows: Some tenants might have unique integrations or settings that alter the application’s behavior.
  • Logging Noise: A centralized logging system can make it difficult to isolate the sequence of events for a single tenant’s problematic …
...

Read more

API Versioning in ASP.NET Core with Custom Middleware

October 15, 2025 · 7 min

As APIs evolve, the need to introduce breaking changes becomes inevitable. The key challenge is to roll out these updates without disrupting existing clients who depend on the current contract. This is where API versioning comes in. While feature-rich libraries like Asp.Versioning.Http are excellent, understanding how to build your own versioning scheme with middleware gives you maximum control and a deeper appreciation for the ASP.NET Core pipeline.

In this post, we’ll explore a clean, middleware-based approach to API versioning using a custom request header. We’ll build a solution that inspects a header and transparently rewrites the request path to route to the correct endpoint implementation.

Why a Middleware Approach?

Dedicated versioning libraries are powerful, offering features like API explorer integration, version advertisement, and conventions. However, a custom middleware solution offers its own set of advantages:

  • Full Control: You define the exact logic for how a version is resolved. You can read it from a header, a claim, a query string, or even a combination of factors.
  • Lightweight: You add only the logic you need, without any extra overhead.
  • Decoupled: The versioning logic lives in one place (the middleware) rather than being scattered across controllers with attributes. This can lead to cleaner endpoint definitions.
  • Great for Learning: Building it yourself is a fantastic way to understand how the ASP.NET Core request pipeline and routing work …
...

Read more

ASP.NET Core Custom Request Validation Middleware

October 14, 2025 · 7 min

In modern ASP.NET Core development, validation is a critical, non-negotiable part of building robust APIs. The default approach often involves using data annotations and checking ModelState within controller actions or using filters. While this works, it can lead to scattered validation logic and boilerplate code, especially in larger applications.

A more powerful and centralized approach is to use custom middleware for request validation. This strategy intercepts requests early in the pipeline, validates them, and rejects them before they even reach your API endpoints. This not only cleans up your endpoint logic but also creates a single, consistent validation gate for your entire application.

In this post, we’ll build a custom validation middleware from scratch, integrating the popular FluentValidation library to create a clean, efficient, and scalable validation system that completely bypasses ModelState.

The Problem with Traditional Validation

The standard [ApiController] attribute in ASP.NET Core automatically triggers model validation and returns a 400 Bad Request if ModelState is invalid. This is convenient but has a few drawbacks:

  • Coupling: The validation logic is tightly coupled to the MVC/API Controller framework. It’s less straightforward to apply the same automatic behavior consistently in Minimal APIs without extra boilerplate.
  • Scattered Logic: Validation rules defined via attributes can become unwieldy and are spread across numerous DTOs.
  • Repetitive …
...

Read more

Master ASP.NET Core Rate Limiting for Robust APIs

October 8, 2025 · 9 min

When you’re building APIs, especially those exposed to the public internet, you’re not just building features; you’re also building defenses. A high-traffic API without protection is vulnerable to everything from accidental infinite loops in a client application to deliberate Denial-of-Service (DoS) attacks. This is where rate limiting becomes an essential part of your application’s architecture.

Starting with .NET 7, ASP.NET Core introduced a powerful and flexible rate-limiting middleware right into the framework. Gone are the days of relying solely on third-party packages or complex manual implementations. Let’s dive into how you can use this middleware to make your APIs more resilient and reliable.

What Exactly is Rate Limiting?

At its core, rate limiting is a defensive mechanism that controls the amount of incoming traffic to your API from a specific source in a given period. It’s like a bouncer at a club who only lets a certain number of people in per minute to prevent overcrowding.

By implementing rate limiting, you can:

  • Prevent Resource Exhaustion: Stop a single user or service from overwhelming your servers, database, or other downstream dependencies.
  • Ensure Fair Usage: Guarantee that all clients get a fair share of the available resources.
  • Improve Security: Mitigate brute-force attacks on login endpoints and reduce the effectiveness of DoS attacks.
  • Manage Costs: If you rely on paid third-party services, rate limiting can prevent …
...

Read more