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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With