Add Response Headers to ASP.NET Core Middleware

前端 未结 6 1339
轻奢々
轻奢々 2020-12-08 06:40

I want to add a processing time middleware to my ASP.NET Core WebApi like this

public class ProcessingTimeMiddleware  
{
    private readonly RequestDelegate         


        
6条回答
  •  猫巷女王i
    2020-12-08 07:07

    Alternatively you can also add a middleware directly in the Startup.cs Configure method.

            app.Use(
                next =>
                {
                    return async context =>
                    {
                        var stopWatch = new Stopwatch();
                        stopWatch.Start();
                        context.Response.OnStarting(
                            () =>
                            {
                                stopWatch.Stop();
                                context.Response.Headers.Add("X-ResponseTime-Ms", stopWatch.ElapsedMilliseconds.ToString());
                                return Task.CompletedTask;
                            });
    
                        await next(context);
                    };
                });
    
            app.UseMvc();
    

提交回复
热议问题