{"id":1741,"date":"2023-06-14T08:37:45","date_gmt":"2023-06-14T08:37:45","guid":{"rendered":"http:\/\/waqar-arshad.com\/?p=1741"},"modified":"2023-08-01T06:59:13","modified_gmt":"2023-08-01T06:59:13","slug":"asp-net-core-middleware","status":"publish","type":"post","link":"http:\/\/waqar-arshad.com\/index.php\/2023\/06\/14\/asp-net-core-middleware\/","title":{"rendered":"Asp.Net Core Middleware"},"content":{"rendered":"<div class=\"pld-like-dislike-wrap pld-template-1\">\r\n    <div class=\"pld-like-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-like-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"1741\" data-trigger-type=\"like\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-up\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-like-count-wrap pld-count-wrap\">    <\/span>\r\n<\/div><div class=\"pld-dislike-wrap  pld-common-wrap\">\r\n    <a href=\"javascript:void(0)\" class=\"pld-dislike-trigger pld-like-dislike-trigger  \" title=\"\" data-post-id=\"1741\" data-trigger-type=\"dislike\" data-restriction=\"cookie\" data-already-liked=\"0\">\r\n                        <i class=\"fas fa-thumbs-down\"><\/i>\r\n                <\/a>\r\n    <span class=\"pld-dislike-count-wrap pld-count-wrap\"><\/span>\r\n<\/div><\/div>\n<h1 class=\"wp-block-heading\">ASP.NET Core &#8211; Middleware<\/h1>\n\n\n\n<p>ASP.NET Core introduced a new concept called&nbsp;<strong>Middleware.<\/strong>&nbsp;A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.<\/p>\n\n\n\n<p>Typically, there will be multiple middleware in ASP.NET Core web application. It can be either framework provided middleware, added via NuGet or your own custom middleware. We can set the order of middleware execution in the request pipeline. Each middleware adds or modifies http request and optionally passes control to the next middleware component. The following figure illustrates the execution of middleware components.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"602\" height=\"214\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/41.png\" alt=\"\" class=\"wp-image-1742\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/41.png 602w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/41-300x107.png 300w\" sizes=\"auto, (max-width: 602px) 100vw, 602px\" \/><\/figure>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/core\/middleware-1.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>ASP.NET Core Middleware<\/p>\n\n\n\n<p>Middlewares build the request pipeline. The following figure illustrates the ASP.NET Core request processing.<\/p>\n\n\n\n<p><a rel=\"noreferrer noopener\" href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/core\/request-processing.png\" target=\"_blank\"><\/a>ASP.NET Core Request Processing<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"602\" height=\"87\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-10.png\" alt=\"\" class=\"wp-image-2164\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-10.png 602w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/08\/image-10-300x43.png 300w\" sizes=\"auto, (max-width: 602px) 100vw, 602px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Configure Middleware<\/h2>\n\n\n\n<p>We can configure middleware in the&nbsp;<code>Configure<\/code>&nbsp;method of the Startup class using&nbsp;<code>IApplicationBuilder<\/code>&nbsp;instance. The following example adds a single middleware using Run method which returns a string &#8220;Hello World!&#8221; on each request.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>Startup<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> Startup()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; } <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;<\/code>public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env, <\/code>ILoggerFactory<code> loggerFactory)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/configure middleware using IApplicationBuilder here..<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;app.Run(<\/code>async<code> (context) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World!\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;});<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>\/\/ other code removed for clarity..<code> <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>In the above example,&nbsp;<code>Run()<\/code>&nbsp;is an extension method on&nbsp;<code>IApplicationBuilder<\/code>&nbsp;instance which adds a terminal middleware to the application&#8217;s request pipeline. The above configured middleware returns a response with a string &#8220;Hello World!&#8221; for each request.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understand Run Method<\/h2>\n\n\n\n<p>We used Run extension method to add middleware. The following is the signature of the Run method:<\/p>\n\n\n\n<p>Method Signature:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public static void Run(this IApplicationBuilder app, RequestDelegate handler)<\/pre>\n\n\n\n<p>The Run method is an extension method on&nbsp;<code>IApplicationBuilder<\/code>&nbsp;and accepts a parameter of&nbsp;<code>RequestDelegate<\/code>. The&nbsp;<code>RequestDelegate<\/code>&nbsp;is a delegate method which handles the request. The following is a RequestDelegate signature.<\/p>\n\n\n\n<p>Method Signature:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public delegate Task RequestDelegate(HttpContext context);<\/pre>\n\n\n\n<p>As you can see above, the&nbsp;<code>Run<\/code>&nbsp;method accepts a method as a parameter whose signature should match with&nbsp;<code>RequestDelegate<\/code>. Therefore, the method should accept the&nbsp;<code>HttpContext<\/code>&nbsp;parameter and return&nbsp;<code>Task<\/code>. So, you can either specify a lambda expression or specify a function in the Run method. The lambda expression specified in the Run method above is similar to the one in the example shown below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>Startup<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> Startup()<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; } <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; app.Run(MyMiddleware);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>Task<code> MyMiddleware(<\/code>HttpContext<code> context) <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> context.Response.WriteAsync(<\/code>\"Hello World! \"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The above&nbsp;<code>MyMiddleware<\/code>&nbsp;function is not asynchronous and so will block the thread till the time it completes the execution. So, make it asynchronous by using&nbsp;<code>async<\/code>&nbsp;and&nbsp;<code>await<\/code>&nbsp;to improve performance and scalability.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/ other code removed for clarity<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp; app.Run(MyMiddleware);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">private<code> <\/code>async<code> <\/code>Task<code> MyMiddleware(<\/code>HttpContext<code> context) <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World! \"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>Thus, the above code snippet is same as the one below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>app.Run(<\/code>async<code> context =&gt; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World!\"<code>) );<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/or <code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>app.Run(<\/code>async<code> (context) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World!\"<code>); <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>});<\/code><\/pre>\n\n\n\n<p>So, in this way, we can configure middleware using&nbsp;<code>Run<\/code>&nbsp;method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Configure Multiple Middleware<\/h2>\n\n\n\n<p>Mostly there will be multiple middleware components in ASP.NET Core application which will be executed sequentially. The Run method adds a terminal middleware so it cannot call next middleware as it would be the last middleware in a sequence. The following will always execute the first Run method and will never reach the second Run method.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; app.Run(<\/code>async<code> (context) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World From 1st Middleware\"<code>); <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;});<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;<\/code>\/\/ the following will never be executed<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; app.Run(<\/code>async<code> (context) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World From 2nd Middleware\"<code>); <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;});<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>To configure multiple middleware, use&nbsp;<code>Use()<\/code>&nbsp;extension method. It is similar to&nbsp;<code>Run()<\/code>&nbsp;method except that it includes next parameter to invoke next middleware in the sequence. Consider the following example.<\/p>\n\n\n\n<p>Example: Use()<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; app.Use(<\/code>async<code> (context, next) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World From 1st Middleware!\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; await next();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; });<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; app.Run(<\/code>async<code> (context) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World From 2nd Middleware\"<code>); <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;});<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The above example will display&nbsp;<code>Hello World From 1st Middleware!Hello World From 2nd Middleware!<\/code>&nbsp;in the browser.<\/p>\n\n\n\n<p>Thus, we can use&nbsp;<code>Use()<\/code>&nbsp;method to configure multiple middlewares in the order we like.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Add Built-in Middleware Via NuGet<\/h2>\n\n\n\n<p>ASP.NET Core is a modular framework. We can add server side features we need in our application by installing different plug-ins via NuGet. There are many middleware plug-ins available which can be used in our application.<\/p>\n\n\n\n<p>The followings are some built-in middleware:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Middleware<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>Authentication<\/td><td>Adds authentication support.<\/td><\/tr><tr><td>CORS<\/td><td>Configures Cross-Origin Resource Sharing.<\/td><\/tr><tr><td>Routing<\/td><td>Adds routing capabilities for MVC or web form<\/td><\/tr><tr><td>Session<\/td><td>Adds support for user session.<\/td><\/tr><tr><td>StaticFiles<\/td><td>Adds support for serving static files and directory browsing.<\/td><\/tr><tr><td>Diagnostics<\/td><td>Adds support for reporting and handling exceptions and errors.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Let&#8217;s see how to use Diagnostics middleware.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Diagnostics Middleware<\/h2>\n\n\n\n<p>Let&#8217;s install and use Diagnostics middleware. Diagnostics middleware is used for reporting and handling exceptions and errors in ASP.NET Core, and diagnosing Entity Framework Core migrations errors.<\/p>\n\n\n\n<p>Open project.json and add Microsoft.AspNetCore.Diagnostics dependency if it is not added. Wait for some time till Visual Studio restores the packages.<\/p>\n\n\n\n<p>This package includes following middleware and extension methods for it.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><td>Middleware<\/td><td>Extension Method<\/td><td>Description<\/td><\/tr><\/thead><tbody><tr><td>DeveloperExceptionPageMiddleware<\/td><td>UseDeveloperExceptionPage()<\/td><td>Captures synchronous and asynchronous exceptions from the pipeline and generates HTML error responses.<\/td><\/tr><tr><td>ExceptionHandlerMiddleware<\/td><td>UseExceptionHandler()<\/td><td>Catch exceptions, log them and re-execute in an alternate pipeline.<\/td><\/tr><tr><td>StatusCodePagesMiddleware<\/td><td>UseStatusCodePages()<\/td><td>Check for responses with status codes between 400 and 599.<\/td><\/tr><tr><td>WelcomePageMiddleware<\/td><td>UseWelcomePage()<\/td><td>Display Welcome page for the root path.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>We can call respective Use* extension methods to use the above middleware in the configure method of Startup class.<\/p>\n\n\n\n<p>Let&#8217;s add welcomePage middleware which will display welcome page for the root path.<\/p>\n\n\n\n<p>Example: Add Diagnostics Middleware<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{&nbsp;&nbsp; <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;app.UseWelcomePage(); <\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;<\/code>\/\/other code removed for clarity <code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>The above example will display the following welcome page for each request.<\/p>\n\n\n\n\n\n<p>This way we can use different Use* extension methods to include different middleware.<\/p>\n\n\n\n<p>Next, learn how to implement logging functionality in the ASP.NET Core application.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Add Custom Middleware in ASP.NET Core Application<\/h1>\n\n\n\n<p>Here, you will learn how to create and add your own custom middleware into the request pipeline of ASP.NET Core application.<\/p>\n\n\n\n<p>The custom middleware component is like any other .NET class with&nbsp;<code>Invoke()<\/code>&nbsp;method. However, in order to execute next middleware in a sequence, it should have&nbsp;<code>RequestDelegate<\/code>&nbsp;type parameter in the constructor.<\/p>\n\n\n\n<p>Visual Studio includes template for creating standard middleware class. For this, right click on the project or folder where you want to create middleware class and select Add -&gt; New Item. This will open Add New Item popup. Search for word &#8220;middleware&#8221; in the top right search box as shown below.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"602\" height=\"367\" src=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/43.png\" alt=\"\" class=\"wp-image-1744\" srcset=\"http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/43.png 602w, http:\/\/waqar-arshad.com\/wp-content\/uploads\/2023\/06\/43-300x183.png 300w\" sizes=\"auto, (max-width: 602px) 100vw, 602px\" \/><\/figure>\n\n\n\n<p><a href=\"https:\/\/www.tutorialsteacher.com\/Content\/images\/core\/custom-middleware.png\" target=\"_blank\" rel=\"noreferrer noopener\"><\/a>Add Custom Middleware<\/p>\n\n\n\n<p>Select Middleware Class item and give it a name and click on Add button. This will add a new class for the middleware with extension method as shown below.<\/p>\n\n\n\n<p>Example: Custom Middleware<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/ You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>MyMiddleware<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>readonly<code> <\/code>RequestDelegate<code> _next;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> MyMiddleware(<\/code>RequestDelegate<code> next)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _next = next;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> Task Invoke(<\/code>HttpContext<code> httpContext)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> _next(httpContext);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/ Extension method used to add the middleware to the HTTP request pipeline.<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>static<code> <\/code>class<code> <\/code>MyMiddlewareExtensions<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>static<code> <\/code>IApplicationBuilder<code> UseMyMiddleware(<\/code>this<code> <\/code>IApplicationBuilder<code> builder)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> builder.UseMiddleware&lt;<\/code>MyMiddleware<code>&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>} <\/code><\/pre>\n\n\n\n<p>As you can see above, the Invoke() method is not asynchronous. So, change it to asynchronous and write your custom logic before calling next();<\/p>\n\n\n\n<p>Example: Async Middleware<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>class<code> <\/code>MyMiddleware<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>readonly<code> <\/code>RequestDelegate<code> _next;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>private<code> <\/code>readonly<code> ILogger _logger;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> MyMiddleware(<\/code>RequestDelegate<code> next, <\/code>ILoggerFactory<code> logFactory)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _next = next;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _logger = logFactory.CreateLogger(<\/code>\"MyMiddleware\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>async<code> <\/code>Task<code> Invoke(<\/code>HttpContext<code> httpContext)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _logger.LogInformation(<\/code>\"MyMiddleware executing..\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>await<code> _next(httpContext); <\/code>\/\/ calling next middleware<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">\/\/ Extension method used to add the middleware to the HTTP request pipeline.<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>static<code> <\/code>class<code> <\/code>MyMiddlewareExtensions<code><\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; <\/code>public<code> <\/code>static<code> <\/code>IApplicationBuilder<code> UseMyMiddleware(<\/code>this<code> <\/code>IApplicationBuilder<code> builder)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>return<code> builder.UseMiddleware&lt;<\/code>MyMiddleware<code>&gt;();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; }<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>} <\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Add Custom Middleware<\/h2>\n\n\n\n<p>Now, we need to add our custom middleware in the request pipeline by using Use extension method as shown below.<\/p>\n\n\n\n<p>Example: Add Middleware into Request Pipeline<\/p>\n\n\n\n<p>&nbsp;Copy<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">public<code> <\/code>void<code> Configure(<\/code>IApplicationBuilder<code> app, <\/code>IHostingEnvironment<code> env)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; app.UseMyMiddleware();<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp; app.Run(<\/code>async<code> (context) =&gt;<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; {<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <\/code>await<code> context.Response.WriteAsync(<\/code>\"Hello World!\"<code>);<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp; });<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>}<\/code><\/pre>\n\n\n\n<p>We can add middleware using&nbsp;<code>app.UseMiddleware&lt;MyMiddleware&gt;()<\/code>&nbsp;method of IApplicationBuilder also.<\/p>\n\n\n\n<p>Thus, we can add custom middleware in the ASP.NET Core application.<\/p>\n\n\n\n<p>Configure the Default File to be Served on the Root Request<\/p>\n\n\n\n<p>As we learned in the Set Default File section,&nbsp;app.UseDefaultFiles()&nbsp;middleware serves the following files on the root request.<\/p>\n\n\n\n<ol class=\"wp-block-list\" type=\"1\">\n<li>Default.html<\/li>\n\n\n\n<li>Default.htm<\/li>\n\n\n\n<li>Index.html<\/li>\n\n\n\n<li>Index.htm<\/li>\n<\/ol>\n\n\n\n<p>Suppose, you want to set home.html as a default page which should be displayed on the root access. To do that, specify&nbsp;DefaultFilesOptions&nbsp;in the&nbsp;UseDefaultFiles&nbsp;method as shown below.<\/p>\n\n\n\n<p>public class Startup<\/p>\n\n\n\n<p>{<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; public void Configure(IApplicationBuilder app, IHostingEnvironment env)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DefaultFilesOptions options = new DefaultFilesOptions();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; options.DefaultFileNames.Clear();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; options.DefaultFileNames.Add(&#8220;home.html&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; app.UseDefaultFiles(options);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; app.UseStaticFiles();<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; app.Run(async (context) =&gt;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; await context.Response.WriteAsync(&#8220;Hello World&#8221;);<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; });<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; }<\/p>\n\n\n\n<p>}<\/p>\n\n\n\n<p>Now, this will display home.html from wwwroot folder on the root request&nbsp;<em>http:\/\/localhost:&lt;port&gt;<\/em>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>ASP.NET Core &#8211; Middleware ASP.NET Core introduced a new concept called&nbsp;Middleware.&nbsp;A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[13],"tags":[],"class_list":["post-1741","post","type-post","status-publish","format-standard","hentry","category-asp-net-core"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"admin","author_link":"http:\/\/waqar-arshad.com\/index.php\/author\/waqar_29_1\/"},"uagb_comment_info":19,"uagb_excerpt":"ASP.NET Core &#8211; Middleware ASP.NET Core introduced a new concept called&nbsp;Middleware.&nbsp;A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed&hellip;","_links":{"self":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1741","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/comments?post=1741"}],"version-history":[{"count":2,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1741\/revisions"}],"predecessor-version":[{"id":2165,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/posts\/1741\/revisions\/2165"}],"wp:attachment":[{"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/media?parent=1741"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/categories?post=1741"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/waqar-arshad.com\/index.php\/wp-json\/wp\/v2\/tags?post=1741"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}