c# - How to change the http status code after starting writing to the HttpContext.Response.Body stream in ASP.NET Core?
问题描述
I often see that writing to the HttpContext.Response.Body
stream is a bad practice (or using PushStreamContent
or StreamContent
as part of a HttpMessageResponse) cause then you cannot change the HTTP status code if there is something wrong happening.
Is there any workaround to actually perform async
writing to the output stream while being able to change HTTP status code in case the operation goes wrong?
解决方案
是的。最佳实践是编写中间件。例如:
public class ErrorWrappingMiddleware
{
private readonly RequestDelegate next;
public ErrorWrappingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next.Invoke(context);
}
catch (Exception exception)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync(...); // change you response body if needed
}
}
}
并将它们注入您的管道
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
...
app.UseMiddleware<ErrorWrappingMiddleware>();
...
}
当然,您可以根据需要更改中间件中的逻辑,包括根据需要更改响应代码。此外,您可以抛出自己的异常类型,例如MyOwnException
,在中间件中捕获然后调用您自己的与您的异常相关的逻辑。
推荐阅读
- ruby-on-rails - 仅在满足条件时如何使用连接
- android - 在 Broadcom 盒子上调用 MediaCodec.release 时避免黑屏
- php - laravel 6中奇怪的路由问题是自己添加路径
- windows - [Windows][NDIS] NdisIfAllocateNetLuidIndex 如何找到新的免费 NetLuidIndex?
- arrays - F#在for循环中为数组赋值
- three.js - 视频球体材料重复不接缝以在 A 帧中工作
- python - Django 自定义模板过滤器 - 如何提及用户和类别
- api - IBM API Connect 是否支持用于处理附件的多部分/表单数据内容类型?
- angular - 无法在 angular8 中导入 PDFmake?
- excel - 将单元格值与工作表名称的一部分进行比较