c# - 将响应 header 添加到 ASP.NET Core 中间件

标签 c# asp.net-core

我想像这样向我的 ASP.NET Core WebApi 添加一个处理时间中间件

public class ProcessingTimeMiddleware  
{
    private readonly RequestDelegate _next;

    public ProcessingTimeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var watch = new Stopwatch();
        watch.Start();

        await _next(context);

        context.Response.Headers.Add("X-Processing-Time-Milliseconds", new[] { watch.ElapsedMilliseconds.ToString() });
    }
}

但是这样做会抛出异常

 System.InvalidOperationException: Headers are readonly, reponse has already started.

如何向响应添加 header ?

最佳答案

没关系,代码在这里

    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);
    }

关于c# - 将响应 header 添加到 ASP.NET Core 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37395227/

相关文章:

C# TCP 客户端到服务器消息

c# - 在 WCF 服务中使用大量数据后清理内存

php - 在 Azure 上运行 ASP.Net Core 和 PHP

asp.net-core - beta6 升级后 DNX 4.5.1 无法解析系统库

c# - "VsTsc"任务无法用其输入 > 参数初始化

sql-server - 我无法从 Visual Studio 2019 登录 Azure 服务

c# - C# 和 C++ 中的分部类在多个 CPP 文件中定义的函数是否相同?

c# - 尝试通过 MVC 应用程序通过 client.CreateDocumentQuery 从 CosmosDb 获取对象

c# - 有没有办法在 Asp.net Core 中执行批处理请求?

c# - 替换 <li> 中的控件