简体   繁体   English

在使用块REST WCF中包装MemoryStream

[英]Wrap MemoryStream in a using block REST WCF

I'm learning REST to implement some Services with WCF. 我正在学习REST以使用WCF实施某些服务。 I implemented an example with a MemoryStream. 我用MemoryStream实现了一个示例。 Because MemoryStream is Disposable I wrapped it in a using. 因为MemoryStream是Disposable,所以将其包装在using中。 When I do this I sometimes can see the xml response in the browser (IE8) and sometimes it will just show me the following Errormessage: 当我这样做时,有时可以在浏览器(IE8)中看到xml响应,有时它只会向我显示以下Errormessage:

The download of the specified resource has failed. 指定资源的下载失败。 Error processing resource ' http://localhost:8889/SimpleGetService/ '. 处理资源' http:// localhost:8889 / SimpleGetService / '时出错。

Why does this occur? 为什么会发生这种情况? When I don't wrap it in a using, I never seem to get the error. 当我不将其包装在使用中时,我似乎永远不会收到错误。

You can set the OperationBehaviorAttribute.AutoDisposeParameters to true . 您可以将OperationBehaviorAttribute.AutoDisposeParameters设置为true This will take of your problem and dispose all returned objects. 这将解决您的问题并处理所有返回的对象。

Edit: Btw: this is set to true by default. 编辑:顺便说一句:默认情况下设置为true So you should not have to worry about it at all anyway :) 因此,您完全不必担心它:)

当您从WCF REST服务返回Stream时,请勿对其进行处理(因为它将在调用者对其进行任何操作之前被处理),只需让框架为您处理即可。

Sounds like it is being disposed before you stream it back to the response. 听起来好像在将其流回响应之前已被处置。 Try getting the bytes from it as a byte array before disposing it and return the bytes. 尝试从中获取字节作为字节数组,然后再处理它并返回字节。

In reality there is absolutely no need to Dispose a MemoryStream as it only uses managed resources. 实际上,绝对不需要处置MemoryStream,因为它仅使用托管资源。 It inherits from Stream so it automatically gets the IDisposable interface, but it is not required. 它从Stream继承,因此它会自动获取IDisposable接口,但这不是必需的。

It seems to me that since the MemoryStream implements IDisposable, you should dispose it. 在我看来,由于MemoryStream实现了IDisposable,因此您应该对其进行处置。 Sure, it doesn't do anything TODAY, but it certainly could soemday! 当然,它今天不做任何事情,但是肯定可以在星期二进行!

You don't want your code to know the nitty-gritty details of making the REST call so maybe you should pull what you need out of the MemoryStream before the end of the using block and return that to your caller. 您不希望您的代码知道进行REST调用的细节,因此也许您应该在using块结束之前从MemoryStream中提取所需的内容,并将其返回给调用者。 That's more loosely-coupled anyway - returning a MemoryStream to your caller exposes too much of the details of the implementation IMHO. 无论如何,这都是松散耦合的-将MemoryStream返回给调用方会暴露太多实现IMHO的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM