Reputation: 2866
I have a WCF Rest Service project set up serving JSON datastructures. I have defined a contract in an interface file like:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "location/{id}")]
Location GetLocation(string id);
Now the WebService needs to return multimedia (images, PDF documents) documents like a standard Web Server does. The WCF WebMessageFormat
of the ResponseFormat
only support JSON or XML. How do i define the method in the interface to return a file ?
Something like:
[OperationContract]
[WebInvoke(Method="GET",
ResponseFormat = ?????
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "multimedia/{id}")]
???? GetMultimedia(string id);
So that: wget http://example.com/multimedia/10
returns the PDF document with id 10.
Upvotes: 6
Views: 2115
Reputation: 7886
You can get a file from your RESTful service as shown below:
[WebGet(UriTemplate = "file")]
public Stream GetFile()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";
FileStream f = new FileStream("C:\\Test.txt", FileMode.Open);
int length = (int)f.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
byte[] buffer = new byte[length];
int sum = 0;
int count;
while((count = f.Read(buffer, sum , length - sum)) > 0 )
{
sum += count;
}
f.Close();
return new MemoryStream(buffer);
}
When you browse to the service in IE it should show a open save dialog for the response.
NOTE: You should set the appropriate content type of the file your service returns. In the above example it return a text file.
Upvotes: 4