Total Page Preview: 000000004642
Explain the difference between app.Run and app.Use in ASP.NET Core
Difference between app.Run and app.Use
In ASP.NET Core, app.Run and app.Use are both methods used in the configuration of the request processing pipeline, which is responsible for handling incoming HTTP requests and generating responses. However, they are used for slightly different purposes.
1-'app.Run' Method:
-
The 'app.Run' method is used to handle the request and generate a response directly. It represents the end of the middleware pipeline.
-
It takes a 'Func<HttpContext', Task> parameter, where you define the logic to process the request and generate a response.
-
If the 'app.Run' method is reached, it means that no subsequent middleware will be executed in the pipeline.
In this example, any request reaching this middleware will respond with "Hello from Run!".
2-'app.Use' Method:
-
The app.Use method is used to add middleware components to the request pipeline. It doesn't terminate the pipeline but passes the request to the next middleware in the pipeline.
-
It takes a Func<HttpContext, Func<Task>, Task> parameter, where you define the middleware logic and call the next middleware using the provided delegate.
-
Multiple app.Use statements can be used to build a chain of middleware components.
In this example, the first app.Use middleware performs some logic before and after calling the next middleware in the pipeline.
The order in which these methods are called matters because it defines the order in which middleware components are executed. Middleware components added with app.Use are executed in the order they are registered, while app.Run represents the terminal point in the pipeline.
Here's a simple example combining both app.Use and app.Run:
In this example, the app.Use middleware will be executed first, and then the app.Run middleware will only be executed if the request has not been handled by previous middleware components.
Thank You
About Author
Brijesh Kumar
Database Developer
I have more then 6 years Experience in Microsoft Technologies - SQL Server Database, ETL
Azure Cloud - Azure SQL Database, CosmosDB, Azure Data Factory, PowerBI, Web Job, Azure Function, Azure Storage, Web Apps, Powershall
and Database Migration On-Premise to Azure Cloud.
LinkedIn : https://www.linkedin.com