Implementing file download via REST endpoint
WCF REST services by default convert the response content of service operations into either XML or JSON format. However, these two formats are definitely not the only formats we can use for responses of REST operations. By customizing the OperationContract
of a service operation, we can make the operation return any arbitrary format of data, such as image, text, ZIP package, or even raw binary files.
In this recipe, we will use a custom REST service that returns files to client consumers as an example to demonstrate how we can use a REST service endpoint to return data in a customized format.
How to do it...
To return custom format data in a WCF REST service, the most important thing is designing the ServiceContract
and OperationContract
to support the response of arbitrary binary format. This can be achieved by changing the return value to System.IO.Stream
type, which is a magic type through which the operation code can return any kind of data...