Home > database >  How does middleware pipeline know what not to execute, when executing in reverse order?
How does middleware pipeline know what not to execute, when executing in reverse order?

Time:08-16

I am watching a guide on pluralsight but there are two things I don't get, how do you run a method in reverse order, and how does middleware pipeline know what not to execute when returning a response? In the example code, when returning a response, it doesn't hit "Before"

public void Configure(IApplicationBuilder app)
{
    app.Use(
        async (context, next) =>
        {
            context.Items.Add("greeting", "Hello World!");
            Console.WriteLine("Before");
            await next.Invoke();
            Console.WriteLine("After");
        });
    app.Run(
        async context =>
        {
            await context.Response.WriteAsync($"The page says {context.Items["greeting"]}");
        });
...

CodePudding user response:

how do you run a method in reverse order, and how does middleware pipeline know what not to execute when returning a response?

It doesn't work like that. The pipeline is illustrated that way sometimes, but it's actually simpler than that.

Each middleware is given a delegate which is the rest of the pipeline. So, each middleware runs the rest of the pipeline in a regular method call: await next.Invoke().

So, when the request is handled, it just executes the first middleware, which displays Before and then executes the rest of the pipeline. When the "downstream" pipeline completes, the middleware method just continues executing and displays "After".

There's no running methods backwards or skipping code going on; middleware is just one method calling another.

  • Related