Writing custom middleware
ASP.NET Core is based on middleware. All the logic that gets executed during a request is based on middleware. So, we can use this to add custom functionality to the web. In the following process, we want to find out the execution time of every request that goes through the request pipeline:
- We can do this by creating and starting a stopwatch before the next middleware is called, and stop measuring the execution time after the next middleware is called, like so:
app.Use(async (context, next) => { var s = new Stopwatch(); s.Start(); // execute the rest of the pipeline await next(); s.Stop(); //stop measuring var result = s.ElapsedMilliseconds; // write out the milliseconds needed await context.Response.WriteAsync($" Time needed: ...