Sample code below to write a file stream to Response.Body
in an ASP.NET Core middleware doesn't work (emits empty response):
public Task Invoke(HttpContext context)
{
context.Response.ContentType = "text/plain";
using (var fs = new FileStream("/valid-path-to-file-on-server.txt", FileMode.Open)
using (var sr = new StreamReader(fs))
{
context.Response.Body = sr.BaseStream;
}
return Task.CompletedTask;
}
Any ideas what could be wrong with this approach of directly setting the context.Response.Body
?
Note: any next middleware in the pipeline is skipped for no further processing.
Update (another example): a simple MemoryStream
assignment doesn't work either (empty response):
context.Response.Body = new MemoryStream(Encoding.UTF8.GetBytes(DateTime.Now.ToString()));
httpContext.Response.SendFileAsync
will work as well, eliminating the need forFileStream
altogether. – Undershrub