简体   繁体   English

如何使用ASP.NET Core进行流式处理

[英]How to stream with ASP.NET Core

How to properly stream response in ASP.NET Core? 如何在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 browsers show Firefox / Edge浏览器显示

Hello World 你好,世界

, while Chrome/Postman report an error: ,Chrome / Postman报告错误:

The localhost page isn't working localhost页面无效

localhost unexpectedly closed the connection. localhost意外关闭了连接。

ERR_INCOMPLETE_CHUNKED_ENCODING ERR_INCOMPLETE_CHUNKED_ENCODING

PS I am about to stream a lot of content, so I cannot specify Content-Length header in advance. PS我即将流式传输大量内容,因此我无法提前指定Content-Length标头。

To stream a response that should appear to the browser like a downloaded file, you should use FileStreamResult : 要将应该在浏览器中显示的响应流式传输为下载文件,您应该使用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"
  };
}

It is possible to return null or EmptyResult() (which are equivalent), even when previously writing to Response.Body . 即使以前写入Response.Body ,也可以返回nullEmptyResult() (它们是等效的)。 It may be useful if the method returns ActionResult to be able to use all the other results aswell (eg BadQuery() ) easily. 如果方法返回ActionResult以便能够轻松地使用所有其他结果(例如BadQuery() ),则可能很有用。

[HttpGet("test")]
public ActionResult Test()
{
    Response.StatusCode = 200;
    Response.ContentType = "text/plain";
    using (var sw = new StreamWriter(Response.Body))
    {
        sw.Write("something");
    }
    return null;
}

I was wondering as well how to do this, and have found out that the original question's code actually works OK on ASP.NET Core 2.1.0-rc1-final , neither Chrome (and few other browsers) nor JavaScript application do not fail with such endpoint. 我也想知道如何做到这一点,并且发现原始问题的代码实际上在ASP.NET Core 2.1.0-rc1-final上运行正常,Chrome(以及其他一些浏览器)和JavaScript应用程序都不会失败这样的终点。

Minor things I would like to add are just set StatusCode and close the response Stream to make the response fulfilled: 我想添加的一些小问题只是设置StatusCode并关闭响应Stream以使响应得到满足:

[HttpGet("test")]
public void Test()
{
    Response.StatusCode = 200;
    Response.ContentType = "text/plain";
    using (Response.Body)
    {
        using (var sw = new StreamWriter(Response.Body))
        {
            sw.Write("Hi there!");
        }
    }
}

something like this might work: 这样的事情可能有用:

[HttpGet]
public async Task<IActionResult> GetTest()
{
    var contentType = "text/plain";
    using (var stream = new MemoryStream(Encoding.ASCII.GetBytes("Hello World")))
    return new FileStreamResult(stream, contentType);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM