gpt4 book ai didi

c# - Web API Core 3.1 ExceptionHandler 中间件在写入 HttpContext.Response 时抛出 'cannot write to closed stream'

转载 作者:行者123 更新时间:2023-12-03 19:16:19 24 4
gpt4 key购买 nike

我有一个简单的 Web API Core v3.1,我试图在其中处理全局异常。遵循此答案后 https://stackoverflow.com/a/55166404/1508398 ,这是我这样做的代码。

 app.UseExceptionHandler(appBuilder => appBuilder.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature.Error;

var result = JsonConvert.SerializeObject(new { error = exception.Message });
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(result);
}));

我得到的错误是 context.Response.WriteAsync(result);是 :

System.ObjectDisposedException: Cannot access a closed Stream.



我很确定我错过了一些基本但无法弄清楚的东西。

我基本上需要在发生异常时将响应包装到一个对象中。

最佳答案

看起来其他人(另一个中间人)已经关闭了流。

在 .net-core 中,排序很重要。请记住您分享的链接:

Important: Remember to add it before UseMvc (or UseRouting in .Net Core 3) as order is important.



所以声明 UseExceptionHandler在任何其他之前 Middlewhate和或配置声明。

Check the middleware guide here

Chain multiple request delegates together with Use. The next parameter represents the next delegate in the pipeline. You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate, as the following example demonstrates:


public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
// Do work that doesn't write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
});

app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.");
});

UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.



第一次运行,终止管道。所以你可以做一些工作,但最终当第一次运行发生时,响应将关闭。

请分享更多代码,以便我们提供更多帮助。

关于c# - Web API Core 3.1 ExceptionHandler 中间件在写入 HttpContext.Response 时抛出 'cannot write to closed stream',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60370694/

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