gpt4 book ai didi

c# - 如何在 asp.net core 中返回自定义 http header ?

转载 作者:行者123 更新时间:2023-12-04 01:51:20 24 4
gpt4 key购买 nike

再见,

我正在使用 aspnet 核心开发一系列微服务。我想在 500 个响应中返回一个自定义的 http header 。

我尝试创建一个自定义 ASP.NET Core 中间件 来更新 context.Response.Headers 属性,但它仅在响应为 200 时有效。

这是我的自定义中间件:

namespace Organizzazione.Progetto
{
public class MyCustomMiddleware
{
private readonly RequestDelegate _next;

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

public async Task InvokeAsync(HttpContext context)
{
context.Response.Headers.Add("X-Correlation-Id", Guid.NewGuid());
await _next.Invoke(context);
return;
}
}
}

这是我的配置方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<MyCustomMiddleware>();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API");
});
}

如何在由未处理的异常(或可能在所有响应)引起的 500 响应中返回我的自定义 header ?

非常感谢

最佳答案

你必须订阅 httpContext.Response.OnStarting

public class CorrelationIdMiddleware
{
private readonly RequestDelegate _next;

public CorrelationIdMiddleware(RequestDelegate next)
{
this._next = next;
}

public async Task Invoke(HttpContext httpContext)
{
httpContext.Response.OnStarting((Func<Task>)(() =>
{
httpContext.Response.Headers.Add("X-Correlation-Id", Guid.NewGuid().ToString());
return Task.CompletedTask;
}));
try
{
await this._next(httpContext);

}
catch (Exception)
{
//add additional exception handling logic here
//...
httpContext.Response.StatusCode = 500;
}

}
}

然后注册你的 Starup

 app.UseMiddleware(typeof(CorrelationIdMiddleware));

关于c# - 如何在 asp.net core 中返回自定义 http header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52893530/

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