Returning no JSON, no XML data in WCF REST service

I have a WCF Rest Service service project configured to serve JSON data structures. I defined the contract in the interface file, for example:

[OperationContract]
[WebInvoke(Method = "GET",
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "location/{id}")]
Location GetLocation(string id);

Now the WebService should return multimedia documents (images, PDF documents), as a standard web server does. WCF WebMessageFormat ResponseFormatonly supports JSON or XML. How to define a method in an interface to return a file?

Sort of:

[OperationContract]
[WebInvoke(Method="GET",
    ResponseFormat = ?????
    BodyStyle = WebMessageBodyStyle.Bare,
    UriTemplate = "multimedia/{id}")]
???? GetMultimedia(string id);

So: wget http://example.com/multimedia/10returns a PDF document with id 10.

+5
source share
1 answer

You can get the file from the 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); 
        }

IE, .

. , . .

+3

All Articles