0

I have api controller, which receives bytes, and sends bytes as answer.

public class RenderController : ApiController
{
    [HttpPost]
    public async Task<HttpResponseMessage> Post(string id)
    {
        var bytes = await Request.Content.ReadAsByteArrayAsync();
        IoSys.Root = new IoSys {InputStream = new MemoryStream(bytes)};
        var model = new DrawingChain().Load();
        IoSys.Root.CloseIn();


        using (var result = Request.CreateResponse(HttpStatusCode.OK))
        {
            using (var stream = new MemoryStream())
            {
                result.Content = new StreamContent(stream)
                {
                    Headers = {ContentType = new MediaTypeHeaderValue("application/octet-stream")}
                };
                IoSys.Root = new IoSys {OutputStream = stream};
                model.Save();
                return result;
            }              
        }
    }

At line of returning a result, client is get a 500 error. I think, I work with streams not properly.

Aminion
  • 465
  • 1
  • 5
  • 13
  • Since it is an async method, consider removing the `using()` from the `result` object. Maybe the .net is disposing it before returning – Felipe Oriani Sep 07 '15 at 22:10

2 Answers2

1

using statement is equivalent of try..finally block. So essentially it's disposing the result object before returning.

Here's a relevant SO thread: When or if to Dispose HttpResponseMessage when calling ReadAsStreamAsync?

Community
  • 1
  • 1
Volkan Paksoy
  • 6,727
  • 5
  • 29
  • 40
1

The objects are being disposed before the returns. Try to update your code in this way:

[HttpPost]
public async Task<HttpResponseMessage> Post(string id)
{
    var bytes = await Request.Content.ReadAsByteArrayAsync();
    IoSys.Root = new IoSys {InputStream = new MemoryStream(bytes)};
    var model = new DrawingChain().Load();
    IoSys.Root.CloseIn();

    var stream = new MemoryStream() // Is it right here?

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    IoSys.Root = new IoSys {OutputStream = stream};
    model.Save();
    return result;
}

Please test it. According to your code, you are assigning a new MemoryStream() without content to the response.

Hernan Guzman
  • 1,235
  • 8
  • 14