Writing a 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. We want to know 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 by stopping 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: {result}"...