---
title: "How to write custom middleware in asp.net core?"  
description: "How to write custom middleware in asp.net core?"  
author: "ICSM Computer"  
published: 2026-03-30  
updated: 2026-03-30  
canonical: https://www.mindstick.com/interview/34485/how-to-write-custom-middleware-in-asp-dot-net-core  
category: "asp.net core"  
tags: ["asp.net mvc", "asp.net core"]  
reading_time: 4 minutes  

---

# How to write custom middleware in asp.net core?

## Step-by-Step: Create Custom Middleware

## 1. Create Middleware Class

```cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System;

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // BEFORE request processing
        Console.WriteLine("Request Incoming: " + context.Request.Path);

        // Call next middleware
        await _next(context);

        // AFTER response processing
        Console.WriteLine("Response Outgoing: " + context.Response.StatusCode);
    }
}
```

## 2. Create Extension Method (Best Practice)

```cs
using Microsoft.AspNetCore.Builder;

public static class CustomMiddlewareExtensions
{
    public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CustomMiddleware>();
    }
}
```

## 3. Register Middleware in Pipeline

### In `Program.cs` (.NET 6+)

```cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseCustomMiddleware();

app.MapGet("/", () => "Hello World!");

app.Run();
```

## Execution Flow

Middleware works like a pipeline:

```plaintext
Request → Middleware1 → Middleware2 → Controller → Middleware2 → Middleware1 → Response
```

## Example: Simple Request Timer Middleware

```cs
using System.Diagnostics;

public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestTimingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();

        await _next(context);

        stopwatch.Stop();

        Console.WriteLine($"Request took {stopwatch.ElapsedMilliseconds} ms");
    }
}
```

## Example: Custom Authentication Check

```cs
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue("ApiKey", out var apiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized");
            return;
        }

        await _next(context);
    }
}
```

## Important Concepts

## 1. Order Matters

Middleware executes in the order added:

```cs
app.UseMiddleware<A>();
app.UseMiddleware<B>();
```

Flow:

```plaintext
A → B → Controller → B → A
```

## 2. Short-Circuiting

Middleware can stop pipeline:

```plaintext
return; // stops next middleware
```

## 3. Dependency Injection Support

```cs
public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<MyMiddleware> _logger;

    public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }
}
```

## When to Use Custom Middleware

- Logging requests/responses
- Global exception handling
- Authentication/authorization
- Rate limiting
- Request validation

## Answers

### Answer by ICSM Computer

## Step-by-Step: Create Custom Middleware

## 1. Create Middleware Class

```cs
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System;

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // BEFORE request processing
        Console.WriteLine("Request Incoming: " + context.Request.Path);

        // Call next middleware
        await _next(context);

        // AFTER response processing
        Console.WriteLine("Response Outgoing: " + context.Response.StatusCode);
    }
}
```

## 2. Create Extension Method (Best Practice)

```cs
using Microsoft.AspNetCore.Builder;

public static class CustomMiddlewareExtensions
{
    public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CustomMiddleware>();
    }
}
```

## 3. Register Middleware in Pipeline

### In `Program.cs` (.NET 6+)

```cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseCustomMiddleware();

app.MapGet("/", () => "Hello World!");

app.Run();
```

## Execution Flow

Middleware works like a pipeline:

```plaintext
Request → Middleware1 → Middleware2 → Controller → Middleware2 → Middleware1 → Response
```

## Example: Simple Request Timer Middleware

```cs
using System.Diagnostics;

public class RequestTimingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestTimingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();

        await _next(context);

        stopwatch.Stop();

        Console.WriteLine($"Request took {stopwatch.ElapsedMilliseconds} ms");
    }
}
```

## Example: Custom Authentication Check

```cs
public class ApiKeyMiddleware
{
    private readonly RequestDelegate _next;

    public ApiKeyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (!context.Request.Headers.TryGetValue("ApiKey", out var apiKey))
        {
            context.Response.StatusCode = 401;
            await context.Response.WriteAsync("Unauthorized");
            return;
        }

        await _next(context);
    }
}
```

## Important Concepts

## 1. Order Matters

Middleware executes in the order added:

```cs
app.UseMiddleware<A>();
app.UseMiddleware<B>();
```

Flow:

```plaintext
A → B → Controller → B → A
```

## 2. Short-Circuiting

Middleware can stop pipeline:

```plaintext
return; // stops next middleware
```

## 3. Dependency Injection Support

```cs
public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<MyMiddleware> _logger;

    public MyMiddleware(RequestDelegate next, ILogger<MyMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }
}
```

## When to Use Custom Middleware

- Logging requests/responses
- Global exception handling
- Authentication/authorization
- Rate limiting
- Request validation


---

Original Source: https://www.mindstick.com/interview/34485/how-to-write-custom-middleware-in-asp-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
