Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of using delegate as parameter for Func in IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)

Tags:

c#

.net-core

In .NetCore we have IApplicationBuilder interface expose the below method used for configuring middleware

IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)

RequestDelegate inturn represents a delegate

public delegate Task RequestDelegate(HttpContext context)

What is the purpose of using Func with delegate as parameter. Wouldnt the below implementation of Use method suffice ? or I'm I missing something here

IApplicationBuilder Use(RequestDelegate delegateVariableName)
like image 498
itsbpk Avatar asked Dec 06 '25 05:12

itsbpk


1 Answers

One of the key points of .Net Core middleware is that you can 'short-circuit' overall pipeline execution, so, each middleware has an opportunity to invoke the next middleware (some kind of "wrapping" this execution in RequestDelegate), or go back. That's why you need Func<RequestDelegate, RequestDelegate>, which is something like app.Use(next => async context => { }), as pointed by @PrabhatSinha in the comments.

Here how it is going:

app.Use(async (context, next) =>
    {
        // Do something before next middleware
        if (someDecision) // decision if we will run next
        {
            await next.Invoke(); // next middleware
            // Do something after next middleware
        }
    });

Just using Use(RequestDelegate delegateVariableName) is not enough. You may read more about this here. This is very good article.

like image 198
vasily.sib Avatar answered Dec 08 '25 17:12

vasily.sib