Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Asp.Net Core

.NET Core Middleware Magic: How to Build Pipeline Filters That Transform Your API

- 05.02.26 - ErcanOPAK

Need consistent request/response handling across all endpoints? Custom middleware creates reusable pipeline components.

Custom Middleware for Global Exception Handling:

// GlobalExceptionMiddleware.cs
public class GlobalExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    private readonly IWebHostEnvironment _env;

    public GlobalExceptionMiddleware(
        RequestDelegate next,
        ILogger logger,
        IWebHostEnvironment env)
    {
        _next = next;
        _logger = logger;
        _env = env;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        _logger.LogError(exception, "Unhandled exception occurred");
        
        context.Response.ContentType = "application/json";
        
        var problemDetails = new ProblemDetails
        {
            Title = "An error occurred",
            Status = GetStatusCode(exception),
            Detail = _env.IsDevelopment() ? exception.Message : "An unexpected error occurred",
            Instance = context.Request.Path,
            Extensions = { ["traceId"] = context.TraceIdentifier }
        };
        
        if (_env.IsDevelopment())
        {
            problemDetails.Extensions["exception"] = new
            {
                exception.Message,
                exception.StackTrace,
                exception.Source,
                InnerException = exception.InnerException?.Message
            };
        }
        
        var json = JsonSerializer.Serialize(problemDetails, new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            WriteIndented = _env.IsDevelopment()
        });
        
        await context.Response.WriteAsync(json);
    }
    
    private static int GetStatusCode(Exception exception) =>
        exception switch
        {
            ValidationException => StatusCodes.Status400BadRequest,
            UnauthorizedAccessException => StatusCodes.Status401Unauthorized,
            KeyNotFoundException => StatusCodes.Status404NotFound,
            InvalidOperationException => StatusCodes.Status400BadRequest,
            NotImplementedException => StatusCodes.Status501NotImplemented,
            _ => StatusCodes.Status500InternalServerError
        };
}

// Extension method for clean registration
public static class GlobalExceptionMiddlewareExtensions
{
    public static IApplicationBuilder UseGlobalExceptionHandler(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware();
    }
}

// Program.cs usage
app.UseGlobalExceptionHandler();
// Place early in pipeline to catch all downstream exceptions

Request/Response Logging Middleware:

// RequestResponseLoggingMiddleware.cs
public class RequestResponseLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public RequestResponseLoggingMiddleware(
        RequestDelegate next,
        ILogger logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Log request
        var request = await FormatRequest(context.Request);
        
        _logger.LogInformation("Request: {Request}", request);
        
        // Copy original response body stream
        var originalBodyStream = context.Response.Body;
        
        using var responseBody = new MemoryStream();
        context.Response.Body = responseBody;
        
        var stopwatch = Stopwatch.StartNew();
        
        try
        {
            await _next(context);
            stopwatch.Stop();
        }
        finally
        {
            // Log response
            var response = await FormatResponse(context.Response);
            
            _logger.LogInformation("Response: {Response} - Duration: {Duration}ms", 
                response, stopwatch.ElapsedMilliseconds);
            
            // Copy the response back to original stream
            responseBody.Seek(0, SeekOrigin.Begin);
            await responseBody.CopyToAsync(originalBodyStream);
        }
    }
    
    private async Task FormatRequest(HttpRequest request)
    {
        request.EnableBuffering();
        
        var body = await new StreamReader(request.Body)
            .ReadToEndAsync();
        
        request.Body.Position = 0;
        
        var headers = request.Headers
            .Where(h => !h.Key.StartsWith("Authorization"))
            .ToDictionary(h => h.Key, h => h.Value.ToString());
        
        return $"{request.Method} {request.Path}{request.QueryString} | " +
               $"Headers: {JsonSerializer.Serialize(headers)} | " +
               $"Body: {body}";
    }
    
    private async Task FormatResponse(HttpResponse response)
    {
        response.Body.Seek(0, SeekOrigin.Begin);
        
        var body = await new StreamReader(response.Body)
            .ReadToEndAsync();
        
        response.Body.Position = 0;
        
        return $"Status: {response.StatusCode} | " +
               $"Headers: {JsonSerializer.Serialize(response.Headers)} | " +
               $"Body: {body}";
    }
}

// Advanced: Filter sensitive data
private string MaskSensitiveData(string input)
{
    var patterns = new Dictionary
    {
        [@"password\":\s*"[^"]*""] = @""password": "***",
        [@"token\":\s * "[^"] * ""] = @""token": " * **",
        [@"creditCard\":\s * "[^"] * ""] = @""creditCard": " * **",
        [@"ssn\":\s * "[^"] * ""] = @""ssn": " * **",
        [@"Bearer\s + [\w\.-] + "] = @"Bearer * **"
    };

            foreach (var pattern in patterns)
            {
                input = Regex.Replace(input, pattern.Key, pattern.Value);
            }

            return input;
        }

Related posts:

.NET Core: Build Background Tasks with Worker Services

.NET Core: Build Background Tasks with Worker Services

ASP.NET Core: Fix a Background Service That Silently Stops Running After One Unhandled Exception

ASP.NET Core: Fix a Background Service That Silently Stops Running After One Unhandled Exception

Asp.Net Core: Fix Antiforgery Tokens Failing Validation Only When Requests Land Behind a Load Balanc...

Asp.Net Core: Fix Antiforgery Tokens Failing Validation Only When Requests Land Behind a Load Balanc...

Views: 14

Post navigation

AI Coding Assistant: ChatGPT Prompts That Generate Production-Ready Code
C# Record Types: Immutable Data Patterns That Eliminate Bugs

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com