Add Response Headers to ASP.NET Core Middleware

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

    In your example headers already sent, when execution reaches context.Response.Headers.Add(...) statement.

    You can try:

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

提交回复
热议问题