本文介绍了如何使用ASP.NET Core进行流传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在ASP.NET Core中正确地流式传输响应?有一个这样的控制器(更新的代码):

How to properly stream response in ASP.NET Core?There is a controller like this (UPDATED CODE):

[HttpGet("test")]
public async Task GetTest()
{
    HttpContext.Response.ContentType = "text/plain";
    using (var writer = new StreamWriter(HttpContext.Response.Body))
        await writer.WriteLineAsync("Hello World");
}

Firefox/Edge浏览器显示

Firefox/Edge browsers show

,而Chrome/Postman报告错误:

, while Chrome/Postman report an error:

localhost意外关闭了连接.

localhost unexpectedly closed the connection.

ERR_INCOMPLETE_CHUNKED_ENCODING

ERR_INCOMPLETE_CHUNKED_ENCODING

P.S.我将要流式传输很多内容,因此无法提前指定Content-Length标头.

P.S. I am about to stream a lot of content, so I cannot specify Content-Length header in advance.

推荐答案

要流式传输应在浏览器中显示的响应,就像下载的文件一样,您应使用FileStreamResult:

To stream a response that should appear to the browser like a downloaded file, you should use FileStreamResult:

[HttpGet]
public FileStreamResult GetTest()
{
  var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World"));
  return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain"))
  {
    FileDownloadName = "test.txt"
  };
}

这篇关于如何使用ASP.NET Core进行流传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 03:23