我正在尝试将使用 PushStreamContent 的 web api 项目(经典 web.config 项目)迁移到最新的 asp.net 5 web 应用程序(project.json)。
我的问题是我无法让 PushStreamContent 工作。
当我使用这个 api 控制器时——结果将以 json 格式结束,而不是流:
[Route("api/[controller]")]
public class EventsController : Controller
{
private static readonly ConcurrentQueue<StreamWriter> s_streamWriter = new ConcurrentQueue<StreamWriter>();
[HttpGet]
public HttpResponseMessage Get(HttpRequestMessage request)
{
HttpResponseMessage response = request.CreateResponse();
response.Content = new PushStreamContent(new Action<Stream, HttpContent, TransportContext>(WriteToStream), "text/event-stream");
return response;
}
private void WriteToStream(Stream outputStream, HttpContent headers, TransportContext context)
{
var streamWriter = new StreamWriter(outputStream) {AutoFlush = true};
s_streamWriter.Enqueue(streamWriter);
}
}
如果我更改控制器操作以返回任务并将 PushStreamContent 包装在 MyPushStreamResult 类中 - 像这样:
[HttpGet]
public async Task<IActionResult> Get(HttpRequestMessage request)
{
var stream = new PushStreamContent(new Action<Stream, HttpContent, TransportContext>(WriteToStream), "text/event-stream");
return new MyPushStreamResult(stream, "text/event-stream");
}
public class MyPushStreamResult : ActionResult
{
public string ContentType { get; private set; }
public PushStreamContent Stream { get; private set; }
public MyPushStreamResult(PushStreamContent stream, string contentType)
{
Stream = stream;
ContentType = contentType;
}
public override async Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = ContentType;
await Stream.CopyToAsync(response.Body);
}
}
对我的控制器操作的请求现在正在返回一个流,但该流在服务器端关闭或包含大量数据之前没有刷新。当我将数据推送到 PushStreamContent 输出流时,我会在每次写入文本后刷新,但我猜刷新不在 response.Body 流上。
我想念什么?找不到任何具有 asp.net 5 结构的示例。