4

I have a file that I am attempting to return to a web client using HttpResponseMessage. The code works, but the transfer speed is five to ten times slower than simply fetching the same file from an IIS virtual directory. I have verified that it's not an encoding issue by monitoring my download bandwidth consumption, which never breaks 250 kilobytes per second, where the direct download from IIS is typically five times that.

Here's the code, stripped to its essentials and with error trapping removed for clarity:

// Succeeded in getting the stream opened, so return with HTTP 200 status to the client.
var stream = new FileStream(uncPath, FileMode.Open,FileAccess.Read, FileShare.Read);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeExtensionHelper.GetMimeType(uncPath)); 
return result;

Am I missing something?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • What does `MimeExtensionHelper.GetMimeType(uncPath)` return? Have you tried hardcoding a value `result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");`? – DaveB Dec 08 '14 at 22:00
  • I would say that your anti-virus is scanning the binary file as it comes in. Disable it and report back. – Mathemats Dec 09 '14 at 04:17
  • 1
    Thanks. It's delivering the correct MIME type - in this case, image/jpeg for most of what it does. I have just found out by experimentation that if I read the entire file into a byte array and use a ByteArrayContent instead of StreamContent the file transfer goes from 13 seconds to under 3 (for a 2.5MB file, transferred from my hosted server to my desktop). So it has something to do with the read buffering of the stream. Giving the stream a large buffer size when opening the file does not help, strangely. It's as though the HttpResponse is reading and writing one byte at a time. – Andrew Forber Dec 09 '14 at 04:32
  • The slowness occurs regardless of antivirus, whether the file in question is on a local or network drive (relative to the web server), or buffer size allocated in the call to the FileStream constructor. It's odd that this should be, by default, so slow. – Andrew Forber Dec 10 '14 at 20:38
  • Did you ever figure this one out? I have posted a similar question here: http://stackoverflow.com/questions/32992081/asp-net-web-api-2-streamcontent-is-extremely-slow – TommyN Oct 13 '15 at 11:40

0 Answers0