gpt4 book ai didi

c# - 当 MVC Core Controller 抛出异常时,如何在中间件中设置不丢弃的 HTTP 响应 header ?

转载 作者:太空宇宙 更新时间:2023-11-03 14:45:03 24 4
gpt4 key购买 nike

以下程序创建了一个简单的 ASP.NET MVC Core 2.2.0 站点,其中包含两个路由:

  • /success - 返回字符串“Success Response”。
  • /failure - 抛出异常,导致返回 500

另外还有一个中间件,它设置了 X-Added-Key/X-Added-Value 的 HTTP 响应 header 。它使用 OnStarting 事件执行此操作,根据 documentation “在将响应 header 发送到客户端之前添加要调用的委托(delegate)。”。

但是,我看到的是,当 MVC 处理 /failure 路由的异常时,我的 HTTP 响应 header 被删除;中间件肯定被命中,但响应缺少 X-Added-Key HTTP 响应 header 。我怀疑这是在做here .

我应该如何设置 HTTP 响应 header ,以便 MVC 在发生异常时不会丢弃它?我在这里的用例是,我们希望返回一个请求 ID,以便 API 使用者在他们想要报告错误时可以给我们一个引用,因此无论 Controller 是否遇到异常都应该返回它。

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace ResponseHeadersSanityCheck
{
internal static class Program
{
static void Main(string[] args)
{
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build()
.Run();
}
}

public sealed class ExampleController : Controller
{
[HttpGet, Route("success")]
public string Success() => "Success Response";

[HttpGet, Route("failure")]
public string Failure() => throw new Exception("Failure Response");
}

public sealed class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

public void Configure(IApplicationBuilder app)
{
app
.Use(async (HttpContext context, Func<Task> next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
return Task.CompletedTask;
});
await next();
})
.UseMvc();
}
}
}

最佳答案

您可以捕获中间件处理之间的异常。

尝试

app.Use(async (HttpContext context, Func<Task> next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
return Task.CompletedTask;
});
try
{
await next();
}
catch (Exception ex)
{

}
}).UseMvc();

更新:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.Use(async (HttpContext context, Func<Task> next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
return Task.CompletedTask;
});
await next();
}).UseMvc();
}

更新:

app.Use(async (HttpContext context, Func<Task> next) =>
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Add("X-Added-Key", "X-Added-Value");
return Task.CompletedTask;
});
//await next();
try
{
await next();
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
}
}).UseMvc();

关于c# - 当 MVC Core Controller 抛出异常时,如何在中间件中设置不丢弃的 HTTP 响应 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762939/

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