Search code examples
c#asp.net-core-mvcmiddlewareasp.net-core-middleware

How to use IApplicationBuilder middleware overload in ASP.NET Core


ASP.NET Core provides two overloads for app.Use() method. Usually we use only one overload that is

app.Use(Func<HttpContext,Func<Task>, Task> middleware)

Which is used as

app.Use(async (context, next) => {
    await context.Response.WriteAsync("1st middleware <br/>");
    await next.Invoke();
});

The other overload that i want to use is

app.Use(Func<RequestDelegate,RequestDelegate> middleware)

I couldn't find an example of how we can use this overload. Any ideas will be great.


Solution

  • Func<RequestDelegate, RequestDelegate> is a delegate, which accepts a delegate and returns a delegate. You can use it with this lambda expression:

    app.Use(next => async context => 
    {
        await context.Response.WriteAsync("Hello, World!");
        await next(context);
    }