Skip to Content
Introduction To ASP.NET Middleware
Adding Terminal Middleware with IApplicationBuilder.Run()

In the previous exercise, we mentioned that each component performs its processing and then has to choose between passing the request to the next delegate in the sequence or short-circuiting the pipeline. The Use() method is dedicated for processing and passing the request to the next delegate. The Run() method, however, is used when passing the request is no longer desired since we may be at the end of the middleware pipeline and need to start returning a response.

Before we dive into the Run() method, let’s first clarify the point that this method does not have to be included in the pipeline. If there is no Run() method, the pipeline will just continue processing until it reaches the last component in the sequence. Similarly, if the Use() method does not invoke the next component the pipeline will be short-circuited and the response will be returned.

The Run() method is simply another way to begin returning the response to the user. Run() is considered terminal middleware because it terminates the pipeline. Remember how we mentioned the importance of properly ordering our components? Well, this concept becomes particularly important when we use the Run() method because any delegates after this component will not be executed.

Check out the example below. Notice the placement of methods inside of Configure(). Do you see how app.Run() appears before app.UseStaticFiles()? The Run() method will kick off processing to start returning a response to the user. Since the response is already being returned, UseStaticFiles() will never get a chance to execute.

public class Startup { public void Configure(IApplicationBuilder app) { app.Run(async (context) => { await context.Response.WriteAsync("Terminal middleware activated!"); }); app.UseStaticFiles(); //Extra code removed for brevity } }



Run the code and examine the results


Now, let’s insert terminal middleware into the pipeline using the app.Run() method. Insert the code shown below between the UseAuthorization() and UseEndpoints() components.

app.Run(async context => { await context.Response.WriteAsync("We've hijacked the pipeline!"); });
Folder Icon

Sign up to start coding

Already have an account?