How to work with ASP.NET Core

How to pass response in ASP.NET Core? There is such a controller ( 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

Hello world

while Chrome / Postman reports an error:

Local page not working

localhost unexpectedly closed the connection.

ERR_INCOMPLETE_CHUNKED_ENCODING

PS I'm going to transfer a lot of content, so I can’t specify the Content-Length header in advance.

+18
source share
5 answers

To convey the response that should be displayed in the browser as 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"
  };
}
+23

null EmptyResult() ( ), Response.Body. , 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;
}
+4

, , , ASP.NET Core 2.1.0-rc1-final, Chrome ( ), JavaScript .

, , StatusCode , :

[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!");
        }
    }
}
+2

This question is a little older, but nowhere could I find a better answer to what I was trying to do. I realized that the trick is to open a new StreamWriter for every piece of content that you would like to write. Just do the following:

[HttpDelete]
public void Content()
{
    Response.StatusCode = 200;
    Response.ContentType = "text/html";

    // the easiest way to implement a streaming response, is to simply flush the stream after every write.
    // If you are writing to the stream asynchronously, you will want to use a Synchronized StreamWriter.
    using (var sw = StreamWriter.Synchronized(new StreamWriter(Response.Body)))
    {
        foreach (var item in new int[] { 1, 2, 3, 4, })
        {
            Thread.Sleep(1000);
            sw.Write($"<p>Hi there {item}!</p>");
            sw.Flush();
        }
    };
}

you can check with curl with the following command: curl -NX DELETE <CONTROLLER_ROUTE>/content

0
source

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);

}
-2
source

Source: https://habr.com/ru/post/1672193/


All Articles