本文介绍了将响应标头添加到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中间件
发布评论