Add Response Headers to ASP.NET Core Middleware

前端 未结 6 1331
轻奢々
轻奢々 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:04

    Using an overload of OnStarting method:

    public async Task Invoke(HttpContext context)
    {
        var watch = new Stopwatch();
    
        context.Response.OnStarting(() =>
        {
            watch.Stop();
    
            context
                  .Response
                  .Headers
                  .Add("X-Processing-Time-Milliseconds",
                            new[] { watch.ElapsedMilliseconds.ToString() });
    
            return Task.CompletedTask;
        });
    
        watch.Start();
    
        await _next(context); 
    }
    

提交回复
热议问题