How to properly dispose the stream when using Stre

2020-02-24 12:15发布

I'm attempting to return a stream from my webapi endpoint, and then clean up by disposing the stream.

I expected this to be the correct way, but the stream is of course disposed before returning.

using(var stream = GetStream()){
    var response = new HttpResponseMessage();
    response.Content = new StreamContent(stream);

    return response;
}

What will be the correct way of disposing the stream?

(Since MSDN says nothing about the behaviour of StreamContent or its methods, my temporary solution is to copy the contents of the stream to a byte array and return that.)

1条回答
劫难
2楼-- · 2020-02-24 12:25

As your only resource that needs to be disposed is the Content of the HttpResponseMessage you don't have to worry about it. The framework does the dispose for you. It will dispose the HttpResponseMessage which will do all the disposing needed. Remove the using and it should work just fine.

The HttpResponseMessage will dispose its Content when it is disposed. See .NET Core implementation

The StreamContent will dispose its stream when it is disposed. See .NET Core implementation of StreamContent

If you need to dispose something not disposed by the HttpResponseMessage you may use request.RegisterForDispose as described by Filip Woj

查看更多
登录 后发表回答