0

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?

8
  • Don't set the response body explicitly when at the same time you are returning action result using File() method. You can set response explicitly in a action filter or a custom middleware, but why? Just use File() method correctly. See this answer to understand how to do it properly. Commented Aug 21, 2024 at 19:45
  • This question is similar to: Return file in ASP.Net Core Web API. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Aug 21, 2024 at 19:45
  • 1
    I didn't find any document to explain how asp.net core calculate content length when we both set Response.Body manually and set return File at the same time. But based on your test(I had a test in my side with your codes too), it's clearly to see that modifying the response stream interferes with how the framework calculates and sets the Content-Length header. I could just say it's better to not set the response body again when we return File(). Commented Aug 22, 2024 at 4:30
  • in addition, you may need file.Position = 0; (I seemed to need that when returning File(memorystream...) When returning a file, it will be streamed so be sure to process the response as such. Commented Aug 22, 2024 at 17:32
  • 1
    Response.Body is 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 replace Response.Body with a random new stream, now there is no connection to the browser. Commented Aug 23, 2024 at 2:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.