Add Response Headers to ASP.NET Core Middleware

前端 未结 6 1336
轻奢々
轻奢々 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条回答
  •  醉酒成梦
    2020-12-08 07:07

    Never mind, the code is here

        public async Task Invoke(HttpContext context)
        {
            var watch = new Stopwatch();
            watch.Start();
    
            //To add Headers AFTER everything you need to do this
            context.Response.OnStarting(state => {
                var httpContext = (HttpContext)state;
                httpContext.Response.Headers.Add("X-Response-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
    
                return Task.CompletedTask;
            }, context);
    
            await _next(context);
        }
    

提交回复
热议问题