Run, Use, and Next Method in ASP.NET Core

Run, Use, and Next Extension Method in ASP.NET Core Application

In this article, I am going to discuss the Run, Use, and Next Extension Method in ASP.NET Core Web API Application. Please read our previous article, where we discussed Middleware Components in ASP.NET Core Web API Application.

Example to understand Run Method in ASP.NET Core:

In order to understand the need and use of the Run, Use, and Next Extension method, please create a new empty ASP.NET Core Web Application by following the below steps.

First, open Visual Studio 2019 and then click on the Create a new project option as shown in the below image.

Example to understand Run Method in ASP.NET Core

Once you click on the Create a new project option, it will open Create a new project window. Here, you can find two projects template for creating an ASP.NET Core Web API project. One is using C# language and the other one is using F# language. I am going to use C# as the programming language, so I select the project template which uses C# Language as shown in the below image.

Run Method in ASP.NET Core

Once you click on the Next button, it will open configure your new project window. Here, you need to specify the Project name (MiddlewareInASPNETCore) and the location where you want to create the project. And then click on the Next button as shown in the below image.

Run Extension Method in ASP.NET Core Web API

Once you click on the Next button, it will open the Additional Information window. Here, I am going with the default configuration, and please make sure to select the Target Framework as .NET 5.0 and click on the Create button as shown in the below image.

Run Extension Method in ASP.NET Core Web API Application

Once you click on the Create button, it will create the ASP.NET Core Web API project with the following file and folder structure.

ASP.NET Core Web API project

Run Method in ASP.NET Core

The Run method in ASP.NET Core Application is used to complete the Middleware Execution. That means the Run extension method allows us to add the terminating middleware component. Terminating middleware means the middleware which will not call the next middleware components in the request processing pipeline.

The Run method is an extension method on the IApplicationBuilder interface and accepts a parameter of RequestDelegate delegate type which actually handles the request. Please have a look at the following image which shows the signature of the Run Extension method.

Run Extension Method in ASP.NET Core Application

The Run Extension method is used for adding terminal middleware that means Adds a terminal middleware delegate to the application’s request pipeline. This method takes two Parameters:

  1. app: The Microsoft.AspNetCore.Builder.IApplicationBuilder instance.
  2. handler: A delegate that handles the request.
Modifying the Configure Method of Startup class:

Let us create a middleware using the Run method. As we already discussed if want to add middleware, then we need to add the same inside the Configure method of the Startup class. Let us add the following Middleware to the Request processing Pipeline.

create a middleware using the Run method

As you can see in the above image, it is a simple middleware created using the Run method. The ASP.NET Core works on async mode, so we need to write the entire code in async in the Run method. Please include Microsoft.AspNetCore.Http namespace for async.

Modify the Configure method of the Startup class as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Run(async context => {
        await context.Response.WriteAsync("Response from Run Middleware");
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

If you notice in the above code, the Run middleware component is configured as the first middleware component. At this moment if you run the application, then you will get the message in the browser which is coming from the Run method as shown in the below image.

Run method in ASP.NET Core Application

As we already discussed the Run method is going to add terminating middleware i.e. it is not going to call the other middleware component configured in the request processing pipeline. To understand this concept, let us add another middleware to the request processing pipeline. So, please modify the Configure method of the Startup class as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Run(async context => {
        await context.Response.WriteAsync("Response from First Run Middleware");
    });

    app.Run(async context => {
        await context.Response.WriteAsync("Response from Second Run Middleware");
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

As you can see in the above code, the first two middleware components are configured using the Run method. When you run the application, it is the first middleware always going to serve the request and as it is configured using the Run method, so it is not going to call the next middleware component configured in the request processing pipeline. So, when you run the application, you will get the following response.

need and use of the Run Extension Method in ASP.NET Core Application

Use() and Next() Extension Methods In ASP.NET Core

The Use Extension Method in ASP.NET Core is used to add a new Middleware component to the Request Processing Pipeline whereas the Next Extension Method in ASP.NET Core is used to call the next middleware component configured in the request processing pipeline.

Use Method:

The Use Extension Method in ASP.NET Core Application allows us to add a new middleware component which may call the next middleware component in the request processing pipeline. The Use extension method adds a middleware delegate defined in-line to the application’s request pipeline. The Use method is also implemented as an extension method on the IApplicationBuilder interface. Following is the signature of the Use extension method:

Use() and Next() Extension Methods In ASP.NET Core

As you can see in the above image, the Use Extension method takes two input parameters. The first parameter is the HttpContext context object using which it accesses both the HTTP request and response. The second parameter is the Func type i.e. it is a generic delegate that can handle the request or call the next middleware component in the request pipeline.

Example to Understand Use Extension Method in ASP.NET Core:

Let us add the following middleware component to the request processing pipeline.

Example to Understand Use Extension Method in ASP.NET Core

With the above Middleware component in place, now our Configure method looks like below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Getting Response from 1st Middleware \n");
    });

    app.Run(async context => {
        await context.Response.WriteAsync("Response Response from second Middleware \n");
    });
}

 

As you can see in the above code, the first middleware component is registered using the Use method while the second middleware component is registered using the Run method. With the above changes in place, now run the application and you should get the following output.

Use Extension Method in ASP.NET Core

As you can see in the above image, the response is coming from the first middleware component i.e. the Middleware registered using the Use extension method. The next Middleware component which is registered using the Run method is not invoked.

Example to understand Next Extension Method in ASP.NET Core

Now the question that should come to your mind is, how to invoke the second middleware component? The answer is by calling the next method from the first middleware component as shown in the below image.

Example to understand Next Extension Method in ASP.NET Core

So, modify the Configure method of the Startup class as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Getting Response from 1st Middleware \n");
        await next();
    });

    app.Run(async context => {
        await context.Response.WriteAsync("Response Response from second Middleware \n");
    });
}

With the above changes in place, now run the application and you should get the response from both the middleware as shown in the below image.

Next Extension Method in ASP.NET Core

If you write some code after the next method, then those code is going to be executed at the returning time. For better understanding, please have a look at the following image.

Understanding Execution Order of Middleware in ASP.NET Core

Let us understand the Request Processing Pipeline in detail with an example. First, modify the Configure method of the Startup class as shown below. As you can see in the below code, here, we are registering three middleware components. The first two middleware components are registered using the Use() Extension method and they are calling the next middleware component using the next method. The last Middleware component is registered using the Run() Extension method which is nothing but the terminating middleware component.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Use Middleware1 Incoming Request \n");
        await next();
        await context.Response.WriteAsync("Use Middleware1 Outgoing Response \n");
    });

    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Use Middleware2 Incoming Request \n");
        await next();
        await context.Response.WriteAsync("Use Middleware2 Outgoing Response \n");
    });

    app.Run(async context => {
        await context.Response.WriteAsync("Run Middleware3 Request Handled and Response Generated\n");
    });
}

Further, if you notice in the above code, we have written some code before and after the next method call in the first two middleware components. Now save the change and run the application and you should get the following response in the browser.

Understanding Execution Order of Middleware in ASP.NET Core

Understanding ASP.NET Core Request Processing Pipeline Execution Order:

In order to understand the request processing pipeline execution order in ASP.NET Core Application, let us compare the above output with the following diagram which we have created in our Middleware in ASP.NET Core article.

Understanding ASP.NET Core Request Processing Pipeline Execution Order

When the incoming HTTP request comes, it is the first middleware that is registered in configure method that will receive the request i.e. Middleware1 which logs the message “Use Middleware1 Incoming Request” in the response stream. So as a result, we see this message first on the browser. Once the first middleware component logs the message to the response stream, then it calls the next() extension method which will invoke the next middleware component configured in the request processing pipeline i.e. Middleware 2 in our example.

The second middleware then logs the message “Use Middleware2 Incoming Request” into the output stream and that what you can see as the second message in the browser. Once it logs the message, then again it calls the next method, which will call the next middleware component registered in the request processing pipeline, and in our example, it is the third middleware component that is registered using the Run extension method.

The third middleware handles the request and then produces the response. So, the third information logs the third message in the browser, and that you can see “Run Middleware3 Request Handled and Response Generated”. As this middleware component is registered using the Run() extension method, so it is going to be a terminal middleware. That is it is not going to call the next middleware component.

So, from this point, the request pipeline starts reversing. That means from Middleware3, the execution control is given back to the previous middleware i.e. Middleware2, and the second middleware will check is there any code after the next method, if yes, then those code gets executed. In our example, it logs the message as “Use Middleware2 Outgoing Response” to the response stream and that you can see as the fourth message in the browser.

Again, once the second middleware complete its execution, the control back to the previous middleware i.e. Middleware1 and the Middleware1 will check is there any code after the next method call and if yes, then those code gets executed. In our example, it logs the message “Use Middleware1 Outgoing Response” to the response stream, and that what you can see as the last message in the browser.

This is how the Use, Next, and Run Method works in ASP.NET Core Application. In the next article, I am going to discuss the Map Extension Method in ASP.NET Core Web API Application. Here, in this article, I try to explain the need and use of the Run, Use, and Next Extension Method in ASP.NET Core Application and I hope you enjoy this Run, Use, and Next Extension Method in the ASP.NET Core Web API Application article.