Learn

Within the lambda expression passed to app.Use() and app.Run(), we can add a next parameter. This allows us to call the “next” middleware in the pipeline.

For example, this middleware does nothing but call the next middleware:

app.Use(async (context, next) => { await next(); });

However in a typical app.Use() expression, there are three steps:

app.Use(async (context, next) => { // i. Do stuff before next middleware await context.Response.WriteAsync("Hello from 1st middleware\n"); // ii. Execute next middleware await next(); // iii. Do stuff after next middleware await context.Response.WriteAsync("Hello again from 1st middleware\n"); });

Now we can start to see the nested aspect of middleware.

Nested middleware

If the above code matches “Middleware 1” in the diagram, then we can trace its execution through both the code and diagram at the same time:

  • Middleware 1 writes to the response (step i. in code and // logic in diagram)
  • Middleware 1 invokes Middleware 2 (step ii. and next();)
  • Middleware 2 and 3 execute, then control is passed back to Middleware 1
  • Middleware 1 writes again to the response (step iii. and // more logic)

We use app.Use() here, but this nested execution happens with all middleware components, including app.UseDeveloperExceptionPage(), app.UseHttpsRedirection(), etc.

Instructions

1.

In this task we are trying to get the output:

Hello from 1st middleware Hello from 2nd middleware Hello from 3rd middleware Hello again from 1st middleware

Currently, the app only writes the first three lines. Let’s enable that final one. Find the first app.Use() call and add this line to the bottom of the expression argument:

await context.Response.WriteAsync("Hello again from 1st middleware\n");
2.

In this task we are trying to get the output:

Hello from 1st middleware Hello from 2nd middleware Hello from 3rd middleware Hello again from 2nd middleware Hello again from 1st middleware

We’re just missing that second to last line. Find the second app.Use() call and add this line to the bottom of the expression argument:

await context.Response.WriteAsync("Hello again from 2nd middleware\n");

Sign up to start coding

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?