Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • ASP.NET Core - Get Started
  • .NET Core Overview
  • ASP.NET Core Overview
  • Install .NET Core
  • Create ASP.NET Core MVC
  • Project Structure
  • wwwroot
  • Program.cs
  • Command-line Interface
  • Dependency Injection
  • Built-in IoC Container
  • Middleware
  • Add Custom Middleware
  • Configure Default File
  • Environment Variable
  • Exception Handling
  • Serving Static Files
  • Serving Static Files From Other Folder
  • Logging in .NET Core
  • Logging in ASP.NET Core
  • .NET Core Application Types
  • Code Sharing
  • Target Multiple Frameworks
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Add Custom Middleware in ASP.NET Core Application

Here, you will learn how to create and add your own custom middleware into the request pipeline of ASP.NET Core application.

The custom middleware component is like any other .NET class with Invoke() method. However, in order to execute next middleware in a sequence, it should have RequestDelegate type parameter in the constructor.

Visual Studio includes template for creating standard middleware class. For this, right click on the project or folder where you want to create middleware class and select Add -> New Item. This will open Add New Item popup. Search for word "middleware" in the top right search box as shown below.

Add Custom Middleware

Select Middleware Class item and give it a name and click on Add button. This will add a new class for the middleware with extension method as shown below.

Example: Custom Middleware
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class MyMiddleware
{
    private readonly RequestDelegate _next;

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

    public Task Invoke(HttpContext httpContext)
    {

        return _next(httpContext);
    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyMiddleware>();
    }
}

As you can see above, the Invoke() method is not asynchronous. So, change it to asynchronous and write your custom logic before calling next();

Example: Async Middleware
public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public MyMiddleware(RequestDelegate next, ILoggerFactory logFactory)
    {
        _next = next;

        _logger = logFactory.CreateLogger("MyMiddleware");
    }

    public async Task Invoke(HttpContext httpContext)
    {
        _logger.LogInformation("MyMiddleware executing..");

        await _next(httpContext); // calling next middleware

    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyMiddleware>();
    }
}

Add Custom Middleware

Now, we need to add our custom middleware in the request pipeline by using Use extension method as shown below.

Example: Add Middleware into Request Pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMyMiddleware();

    app.Run(async (context) =&gt;
    {
        await context.Response.WriteAsync("Hello World!");
    });
}

We can add middleware using app.UseMiddleware<MyMiddleware>() method of IApplicationBuilder also.

Thus, we can add custom middleware in the ASP.NET Core application.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.