Saturday, 23 January 2021

Part 7 : Custom Middlware in asp.net Core application

I’m using the same example, also shared sample code on Github. Before starting with custom lets understand Run middlware, we discussed in previous article run middlware is used to terminate http request and return response or we can say short cercuit the request. Run middlware not passing request to next middleware instead it terminate. Lets understand with example.


Remove everything from configure method.


Add below code in configure method.

app.Run(async (context) =>

            {

                await context.Response.WriteAsync("Hello from Run middleware 1");

            });

 

Now run application and check response message on browser.


Add few more Run middleware and check response message on browser window. It short circuit http request pipeline and return response from 1st middleware.


If all three response want to print on browser window. To achieve this use Use() middleware shown in below screen.


 next() method is used to pass http request to next middleware in pipeline. 

Both Run or Use middleware can be used to achieve purpose of custom middleware. As Run middleware terminate http request better use Use middleware for custom logic (custom middleware). 

Add below class with startup.cs or anywhere in project.

public class CustomMiddleware

    {

        public static Task UserMiddleware(HttpContext context)

        {

            // Add logic for custom middleware

            return context.Response.WriteAsync("Hello from custom middleware");

        }

    } 

Below screen shows calling custom logic or piece of code from Use middleware.


Previous                                                                                                                                               Next

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home