qqqqqqq
qqqqqqq

Reputation: 2227

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>();
    }
} 

Upvotes: 4

Views: 8894

Answers (1)

Nkosi
Nkosi

Reputation: 247461

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.

Upvotes: 9

Related Questions