【发布时间】:2016-07-06 08:13:53
【问题描述】:
我在使用 Asp.net core 1.0 RTM 时遇到了困难。例如,在下面的情况下,我们将看到输出结果为“-Message_1--Message_5-”:
public class MessageMiddleware
{
private readonly RequestDelegate _next;
private readonly IApplicationBuilder _app;
public MessageMiddleware(RequestDelegate next, IApplicationBuilder app)
{
_next = next;
_app = app;
}
public async Task Invoke(HttpContext context)
{
var started1 = context.Response.HasStarted;//false
await context.Response.WriteAsync("-Message_1-");
var test = true; // will hit this line
var started2 = context.Response.HasStarted;//true
await context.Response.WriteAsync("-Message_5-");
await _next.Invoke(context);
}
}
但在这种情况下(添加了标题“Content-Type”)结果将只有“-Message_1-”并且执行真的停止了:
public class MessageMiddleware
{
private readonly RequestDelegate _next;
private readonly IApplicationBuilder _app;
public MessageMiddleware(RequestDelegate next, IApplicationBuilder app)
{
_next = next;
_app = app;
}
public async Task Invoke(HttpContext context)
{
var started1 = context.Response.HasStarted;//false
await context.Response.WriteAsync("-Message_1-");
var started2 = context.Response.HasStarted;//true
context.Response.ContentType = "text/html";
var test = true; // will NOT hit this line
var started3 = context.Response.HasStarted;//will NOT hit this line
await context.Response.WriteAsync("-Message_5-"); //will NOT hit this line
await _next.Invoke(context);
}
}
我在官方文档中只找到了这句话:
避免在调用下一个之后修改 HttpResponse,管道中的下一个组件之一可能已写入响应,导致它被发送到客户端。
这个问题在 SO:Why can't the HttpResponse be changed after 'next' call?
但是仅仅了解在中间件管道期间与 HttpContext.Response 的 props 的交互以及这种交互如何影响最终结果 - HttpResponse 的标头和正文内容是不够的。
有人可以解释 ASP.NET 核心处理响应的一般行为吗?例如,当响应标头发送到客户端时,设置 HttpContext.Response 属性(标头,正文内容)对此有何影响? 当管道内(外)中间件终止时?
谢谢!
【问题讨论】:
-
在向响应流写入内容后不要设置标头。您只能在数据发送到客户端之前设置标头。一旦您向客户端发送任何数据,您就不能再更改或设置标头,因为需要在发送内容之前设置标头(它们在内容之前提交)
-
曾,向客户端发送数据时发出事件?你是什么意思“发送数据”?是否只发送标头?观察者在哪里以及它是如何工作的?
-
await context.Response.WriteAsync("-Message_1-");,取决于您是否拥有(或没有)任何缓冲的中间件。即使那样,您也无法控制它何时被刷新。之后的一行context.Response.ContentType = "text/html";正在设置标题在内容已写入
标签: asp.net-core response middleware pipeline