将响应标头添加到ASP.NET Core中间件

编程入门 行业动态 更新时间:2024-10-24 12:24:36
本文介绍了将响应标头添加到ASP.NET Core中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

但是这样做会抛出一个异常提示

But doing this throws an exception saying

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

如何在响应中添加标题?

How can I add headers to the response?

推荐答案

没关系,代码在这里

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

更多推荐

将响应标头添加到ASP.NET Core中间件

本文发布于:2023-11-05 09:51:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560522.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中间件   ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!