Kestrelhttpserver: InvalidOperationException: Response Content-Length mismatch when streaming a bitmap

Created on 21 Sep 2017  路  5Comments  路  Source: aspnet/KestrelHttpServer

Hi there,

If one tries to return an image in a FileStreamResult, the application will throw an exception along the lines of:
InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 1234567)

My code was as follows:
```c#
private static IActionResult ImageResult(Bitmap image, ImageFormat format, string mimeType)
{
var stream = new MemoryStream();
image.Save(stream, format);
return new FileStreamResult(stream, mimeType);
}

However, if I changed it to the following,  the image is returned without complaint:
```c#
private static IActionResult ImageResult(Bitmap image, ImageFormat format, string mimeType)
{
    var stream = new MemoryStream();
    image.Save(stream, format);
    return new FileContentResult(stream.ToArray(), mimeType);
}

It appears that doing the reading manually fixes the issue.

Thanks!

Most helpful comment

Did you forget to Seek the stream back to the beginning?

All 5 comments

Did you forget to Seek the stream back to the beginning?

Yep that would do it!

Sorry to take up your time!

I get the same exception one out of two requests. It only happens when I deploy my application to Azure app service. Unfortunately, I can't reproduce it locally.

public class HomeController : Controller
{
    public IActionResult Spa()
    {
        return File("~/index.html", "text/html");
    }
}

@HWouters that looks like a different issue. See https://github.com/aspnet/Mvc/issues/6875

@Tratcher thank you for pointing me to the right issue. The workaround solves my problem until the patch is released.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nmilosev picture nmilosev  路  9Comments

halter73 picture halter73  路  5Comments

fabiobraganet picture fabiobraganet  路  7Comments

M-Curtis picture M-Curtis  路  3Comments

txdv picture txdv  路  7Comments