I have an endpoint with the following code:
var range = Request.GetTypedHeaders().Range;
var file = new MemoryStream(Enumerable.Range(0, 255).Select(x => (byte)x).ToArray());
// Response.Body = file;
return File(file, "application/octet-stream", "{{1.txt}}", null, new EntityTagHeaderValue($"\"1.txt\""), true);
And this is how I send request to it:
var request = new HttpRequestMessage { RequestUri = new Uri("http://localhost:5100/file") };
request.Headers.Range = new RangeHeaderValue(0, 100);
var response = new HttpClient().SendAsync(request).Result;
Debug.WriteLine($"ContentLength: {response.Content.Headers.ContentLength}");
Debug.WriteLine(response.RequestMessage);
The print out is:
ContentLength: 100
Method: GET, RequestUri: 'https://localhost:7165/file', Version: 1.1, Content: <null>,
Headers:
{
Range: bytes=0-100
}
But if I uncomment line with Response.Body = file content length becomes 0. Why?
File()method. You can set response explicitly in a action filter or a custom middleware, but why? Just useFile()method correctly. See this answer to understand how to do it properly.Response.Bodyis an existing stream that you can write to, which will cause the response to be written to the https stream and to the browser. If you replaceResponse.Bodywith a random new stream, now there is no connection to the browser.