How to read stream from WCF service
I have created a WCF service to stream files(download). Code for the service is below
public Stream GetCoverScan(List<string> productIDs)
{
FileStream stream = new FileStream("", FileMode.Open, FileAccess.Read);
return stream;
}
Can some one tell me how do i consume this on the client side. I have already created a proxy on client and i can see the method by creating an object of the service, but how do i read the stream.
Please advise
Configuration
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="StreamedHttp" transferMode="StreamedResponse"
maxReceivedMessageSize="67108864">
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="Streaming.Service1"
behaviorConfiguration="Streaming.Service1Behavior">
<endpoint address="" bindingConfiguration="StreamedHttp"
binding="basicHttpBinding" contract="Streaming.IService1">
</endpoint&开发者_StackOverflow社区gt;
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Streaming.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Contract
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(string name);
[OperationContract]
System.IO.Stream GetCoverScan(List<string> productIDs);
}
bindings
</bindings>
You need to configure streaming on the binding you use. Streaming is supported for BasicHttpBinding
, NetTcpBinding
, and NetNamedPipeBinding
. So if you have a BasicHttpBinding
, your configuration should look like this:
<basicHttpBinding>
<binding name="HttpStreaming" maxReceivedMessageSize="67108864"
transferMode="StreamedResponse"/>
</basicHttpBinding>
I use StreamedResponse
here because you only have a response that should be a stream, not a request.
How you read the stream itself depends on what's in it. Suppose you send a text file over a stream, you can use a StreamReader
:
var reader = new StreamReader(service.GetCoverScan(...));
string contents = reader.ReadToEnd();
If you send an xml file, you can read it through XDocument
:
var doc = XDocument.Load(service.GetCoverScan(...));
So it really depends on what you're sending over the wire.
If you mention
response.ContentType = "text/xml"
just before returning stream, the receiving application can know the type of the stream thus can invoke standard way of stream as a reference.
精彩评论