gpt4 book ai didi

c# - 在 ASP .Net Core 中的 ExceptionFilterAttribute 中添加响应 header

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:02 27 4
gpt4 key购买 nike

我正在尝试在发生异常时向来自 .Net 核心 Web API 的响应添加 header 。

我正在使用 ExceptionFilterAttribute...

public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
context.HttpContext.Response.Headers.Add("CorrelationId", "12345");
base.OnException(context);
}
}

由于某种原因, header 没有发送到客户端。我猜这与此时已经形成的响应有关,因此无法更改?

我有一个自定义中间件,可以将关联 ID 添加到请求上下文,然后将其输出到响应 header 中。这不会在发生异常时触发,所以我需要另一种方法来尝试使用过滤器。

我应该更改什么才能使其正常工作?

最佳答案

试试这个,

  public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
var correlationId = "12345";

// DO OTHER STUFF

context.HttpContext.Response.OnStarting(() =>
{
context.HttpContext.Response.Headers.Add("CorrelationId", correlationId);
return Task.CompletedTask;
});
}
}

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com