在ASP.NET核心中间件中设置响应状态
发布时间:2020-10-19 07:42:32 所属栏目:asp.Net 来源:互联网
导读:我有一个中间件,它隐藏了客户端的异常,并在出现任何异常时返回500错误: public class ExceptionHandlingMiddleware{ private readonly RequestDelegate _next; public ExceptionHandlingMiddleware(RequestDelegate next) {
|
我有一个中间件,它隐藏了客户端的异常,并在出现任何异常时返回500错误: public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception exception)
{
var message = "Exception during processing request";
using (var writer = new StreamWriter(context.Response.Body))
{
context.Response.StatusCode = 500; //works as it should,response status 500
await writer.WriteAsync(message);
context.Response.StatusCode = 500; //response status 200
}
}
}
}
我的问题是,如果我在写主体之前设置响应状态,客户端将看到此状态,但如果我在向主体写入消息后设置状态,则客户端将收到状态为200的响应. 有人可以解释一下为什么会这样吗? 附:我正在使用ASP.NET Core 1.1 解决方法当你知道HTTP是如何工作的时候那就是设计.标头位于数据流的开头(见wiki example).发送数据后,您无法更改/修改标头,因为数据已通过网络发送. 如果要稍后设置它,则必须缓冲整个响应,但这会增加内存使用量.这里有关于如何将流交换为内存流的a sample. (编辑:日照站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net – GetExternalLoginInfoAsync()loginInfo返回null
- asp.net-mvc-3 – System.Web.Mvc.HandleErrorInfo错误的模
- asp.net – 在VS Code中指定localhost端口的位置
- Asp.net下使用Jquery Ajax传送和接收DataTable的代码
- asp.net-mvc – ASP.NET MVC 2预览2:区域重复控制器问题
- ASP.Net Web应用程序安全性不适用于IIS 7?
- asp.net-mvc – 在布局视图中获取当前的ApplicationUser
- ASP.NET MVC Url路由支持(点)
- dependency-injection – 从ILogger访问当前的HttpContext
- asp.net – CalendarExtender定位问题
推荐文章
站长推荐
热点阅读
