Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 331
Azmat Ullah Avatar asked Mar 20 '17 08:03

Azmat Ullah


People also ask

How do I put middleware in NET Core?

Search for word "middleware" in the top right search box as shown below. 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.

What is true about IApplicationBuilder use () and IApplicationBuilder run ()?

Run() is an extension method on IApplicationBuilder instance which adds a terminal middleware to the application's request pipeline. The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate.

What happens when a terminal middleware is used in the request pipeline?

Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain actions before and after the next component is invoked in the pipeline.

What is request delegate in ASP.NET Core?

In ASP.NET Core, Request delegates are used to build the request pipeline i.e. request delegates are used to handle each incoming HTTP request. In ASP.NET Core, you can configure the Request delegates using the Run, Map, and Use extension methods.


1 Answers

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);
}
like image 128
Henk Mollema Avatar answered Oct 27 '22 01:10

Henk Mollema