gpt4 book ai didi

c# - Web API 全局错误处理在响应中添加自定义 header

转载 作者:太空狗 更新时间:2023-10-29 23:50:28 26 4
gpt4 key购买 nike

我想知道是否可以在发生内部服务器错误时设置一些自定义 header 值?我目前正在做:

public class FooExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
// context.Result already contains my custom header values
context.Result = new InternalServerErrorResult(context.Request);
}
}

这里我还想设置一些 header 值,但尽管它出现在请求中,但响应不包含它。

有没有办法做到这一点?

最佳答案

有示例代码供你引用,我的ApiExceptionHandler就是你的FooExceptionHandler

    public class ApiExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var response = new Response<string>
{
Code = StatusCode.Exception,
Message = $@"{context.Exception.Message},{context.Exception.StackTrace}"
};

context.Result = new CustomeErrorResult
{
Request = context.ExceptionContext.Request,
Content = JsonConvert.SerializeObject(response),
};
}
}

internal class CustomeErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }

public string Content { get; set; }

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response =
new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(Content),
RequestMessage = Request
};

response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "*");

return Task.FromResult(response);
}
}

关于c# - Web API 全局错误处理在响应中添加自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31653091/

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