Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it recommended for a middleware to be async in ASP.NET Core?

Why is it recommended for a middleware to be async in ASP.NET Core?

E.g. in this tutorial it is recommended to make the middleware custom and I can not understand the reason behind it.

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>();
    }
} 
like image 902
qqqqqqq Avatar asked Oct 15 '25 20:10

qqqqqqq


1 Answers

According to the documentation, that is by design

The middleware class must include:

  • A public constructor with a parameter of type RequestDelegate.
  • A public method named Invoke or InvokeAsync. This method must:
    • Return a Task.
    • Accept a first parameter of type HttpContext.

Reference Write custom ASP.NET Core middleware

My understanding is that the pipeline has been designed to be async by default.

RequestDelegate which is the core of asp.net core's pipe line requires a Task in order to allow a high-performance, and modular HTTP request pipeline.

public delegate System.Threading.Tasks.Task RequestDelegate(HttpContext context);

From Comments: credit to @ScottChamberlain

The reason is that with how async was built in to asp.net core it allows for more throughput of web requests for the same hardware when comparing to a non async version.

like image 84
Nkosi Avatar answered Oct 17 '25 08:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!