none
WCF REST Template 4 POST bitmap

    Question

  • I want to receive a bitmap image from a device with a WCF REST Template method, something like this:
            [WebInvoke(UriTemplate = "photo", Method = "POST")]
            public void CreatePhoto(Stream bmpData)   
            {
                if (data == null)
                {
                    data = new ControlClasses.ImageDataItem();
                }
    
                BinaryReader reader = new BinaryReader(bmpData);
                data.bytes = reader.ReadBytes((int)bmpData.Length);
                data.TimeReceived = DateTime.Now;
            }
    
    

    The ControlClasses.ImageDataItem is an in-memory object on the service.
    I've used two different methods to send the POST.  Sometimes I get status code 400 and sometimes 500 errors.  How does this work?

    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Edited by Mike Dodaro Thursday, December 22, 2011 4:27 PM
    Thursday, December 22, 2011 4:20 PM

Answers

  • Hi!

    Try returning a Stream with Bitmap bytes from the server:

    [WebGet(UriTemplate = "{id}", BodyStyle = WebMessageBodyStyle.Bare)]
    public Stream Get(string id)
    {
            try
            {
                if (itemList.Count > 0)
                {
                    MemoryStream stream = new MemoryStream(itemList[int.Parse(id)].BitmapData);                    
                    return stream;                                        
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
    }
    

    Then, on the client, you can write something like this:

    private void btnGetFile_Click(object sender, EventArgs e)
    {
        string uri = string.Format("{0}photos", BASE_ADDRESS);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri + "/12");
    
        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            pictureBox1.Image = System.Drawing.Image.FromStream(response.GetResponseStream());
        }
    }
    

    This works correctly for me.


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    • Marked as answer by Mike Dodaro Friday, December 30, 2011 3:19 PM
    Friday, December 30, 2011 11:48 AM

All replies

  • You'll need to enable tracing (http://msdn.microsoft.com/en-us/library/ms733025.aspx) at the server; the traces will have an exception explaining why the server rejected the request.
    Carlos Figueira
    Thursday, December 22, 2011 5:09 PM
  • This service runs on a remote IIS server.  Trying to run traces on the ASP.NET development server, I don't get any log file. 


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Thursday, December 22, 2011 6:11 PM
  • You should have some traces. Check a couple of things:

    • The account on which IIS is running (normally "NETWORK USER") has write access to the folder where the trace file is supposed to be written (the "initializeData" parameter as shown in the page). If it doesn't have write access, you won't get any traces
    • Try adding <trace autoflush="true"/> under the <system.diagnostics> section, that will prevent in-memory buffering of the traces and you'll get the complete traces for your application.

    Carlos Figueira
    Thursday, December 22, 2011 6:45 PM
  • I made the change, but still not getting a log file.  Cassini should have access to the following:
            <listeners>
              <add name="traceListener"
                  type="System.Diagnostics.XmlWriterTraceListener"
                  initializeData= "C:\Users\Public\Documents\Traces.svclog" />
            </listeners>
    


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Thursday, December 22, 2011 6:54 PM
  • I'd like to figure this out because the new WCF REST Service template has been working great for me with everything except a POST with data in the body.  The GET methods work fine and so do POSTs for updating data on the server until I try to put something in the body of the request.  Do you have some documentation on the template that explains the POST implementation?
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Thursday, December 22, 2011 11:19 PM
  • Cassini usually only works within the same machine; you mentioned that your server is running on a remote IIS server. Can you check that you're making the change on the correct machine / location?
    Carlos Figueira
    Thursday, December 22, 2011 11:21 PM
  • Yeah, I'm just trying to get the pieces working using cassini with this POST issue. The GET and other POSTs work fine on the remote server.
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Thursday, December 22, 2011 11:22 PM
  • Ok, I've got tracing enabled on the remote server and set to verbose output, but all it tells me so far is what I already know. One warning.  Evidently I don't have enough rules set up.  What kind of tracing rules do I need?

    ModuleName ManagedPipelineHandler
    Notification 128
    HttpStatus 400
    HttpReason Bad Request
    HttpSubStatus 0
    ErrorCode 0
    ConfigExceptionInfo  
    Notification EXECUTE_REQUEST_HANDLER
    ErrorCode

    The operation completed successfully. (0x0)

     


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Friday, December 23, 2011 7:49 PM
  • The service method I'm using is the following, and I'm sending the POST from Fiddler2 with .bmp file in the body.
            [WebInvoke(UriTemplate = "", Method = "POST")]
            public void Create(Stream streamInput) 
            {
                if (imageItem == null)
                {
                    imageItem = new ImageItem();
                }
    
                long length = WebOperationContext.Current.IncomingRequest.ContentLength;
                BinaryReader reader = new BinaryReader(streamInput);
                byte[] bytes = new byte[length];
    
                reader.Read(bytes, 0, (int)length);
                imageItem.imageData = bytes;
                imageItem.timeSent = DateTime.Now;
    
             }
    


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Friday, December 23, 2011 8:05 PM
  • Here is another way I'm trying to send the data after trying fiddler without success.  I can't get any binary data to post, though I can post a string.

    using System;
    using System.Net;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                HttpWebRequest request =
                                 WebRequest.Create("http://localhost:33285/Service1/") as HttpWebRequest;
    
                request.Method = "POST";
                
                FileStream bmpFile = new FileStream(@"Image-14.bmp", FileMode.Open);
                BinaryReader reader = new BinaryReader(bmpFile);
                byte[] bytes = reader.ReadBytes((int)bmpFile.Length);
    
                request.ContentLength = bytes.Length;
                request.ContentType = "image/bmp";
    
                Stream requestStream = request.GetRequestStream();
    
                requestStream.Write(bytes, 0, bytes.Length);
    
                HttpWebResponse response;
                try
                {
                    response = request.GetResponse() as HttpWebResponse;
    
                    Console.WriteLine("Reaponse status code: " + response.StatusCode);
    
                    response.Close();
                }
                catch (Exception ex)
                {
                    string exception = ex.Message + " Inner:" + ex.InnerException;
                    Console.WriteLine(exception);
                    
                }
                
            }
        }
    }
    


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Friday, December 23, 2011 10:22 PM
  • I can POST the binary contents of a text file to the service and it works fine, but when I try to send a bitmap as binary, it fails.

    I can also send the binary contents of a .gif file and it works. Why does it choke on .bmp or .jpg binary?

     Current version of method on service follows:

     

            [WebInvoke(UriTemplate = "", Method = "POST")]
            public string Create(Stream data)
            {
    
                if (itemList == null)
                {
                    itemList = new List<SampleItem>();
                }
    
                SampleItem item = new SampleItem();
                item.Id = itemList.Count + 1;
    
                BinaryReader reader = new BinaryReader(data);
                byte[] bytes = new byte[WebOperationContext.Current.IncomingRequest.ContentLength];
                bytes = reader.ReadBytes((int)WebOperationContext.Current.IncomingRequest.ContentLength);
                //item.bmpImage = new Bitmap(data);
                item.StringValue = "new test item ####" + item.Id;
                item.timeSent = DateTime.Now;
    
                itemList.Add(item);
                return item.StringValue;
            }


    This posting is provided "AS IS" with no warranties, and confers no rights.

     


    • Edited by Mike Dodaro Saturday, December 24, 2011 12:52 AM
    Saturday, December 24, 2011 12:37 AM
  • Hi Mike!

    Could the problem be related with the dimension of the file you are trying to trasmit?


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Saturday, December 24, 2011 12:53 AM
  • Hi!
    Perhaps I have found a solution. It seems that the problem is related to the dimension of the file. Try the following way:
    1. In the web.config of the WCF Rest Service, change the standardEndpoint tag as follows:
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="4194304" transferMode="Buffered" />
    

    In particular, note the maxReceivedMessageSize attribute, that specifies that the maximum size of a message is 4 MB.
    2. Define in the service an UploadFile method like this:
    [WebInvoke(UriTemplate = "UploadFile/{fileName}", Method="POST")]
    public void UploadFile(string fileName, Stream fileContents)
    {
        byte[] buffer = new byte[32768];
        MemoryStream ms = new MemoryStream();
        int bytesRead, totalBytesRead = 0;
        do
        {
            bytesRead = fileContents.Read(buffer, 0, buffer.Length);
            totalBytesRead += bytesRead;
            
            ms.Write(buffer, 0, bytesRead);
        } while (bytesRead > 0);
    
        // Save the file to drive D:.
        File.WriteAllBytes(@"D:\" + fileName, ms.ToArray());
        ms.Close();
        Console.WriteLine("Uploaded file {0} with {1} bytes", fileName, totalBytesRead);
    }
    
    I have noticed that this code, with the do-while cycle, is the only way in which the method works correctly.
    3. To test the service, use the following example:
    // BASE_ADDRESS if the address of the server that hosts the server.
    // photos is the name of the service as define in Global.asax file.
    string uri = string.Format("{0}photos", BASE_ADDRESS);
    
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri + "/UploadFile/Nuovo.jpg");
    request.Method = "POST";
    request.ContentType = "text/plain";
    
    // Read a file located in drive D:. Modify this path to specify a valid image in your system.
    byte[] fileToSend = File.ReadAllBytes(@"D:\img18.jpg");
    request.ContentLength = fileToSend.Length;
    
    using (Stream requestStream = request.GetRequestStream())
    {
        // Send the file as body request.
        requestStream.Write(fileToSend, 0, fileToSend.Length);
        requestStream.Close();
    }
    
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
    
    

    Using this code, I was able to correctly transimt a 1.5 MB bitmap file to server.


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Sunday, December 25, 2011 6:11 PM
  • Thanks, Marco!  This looks as good as gift from Santa Claus.  I will give it a try as soon as I get over a very sumptuous Christmas dinner.
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Monday, December 26, 2011 6:22 AM
  • OK, let me know if this code resolves your problem :-)
    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Monday, December 26, 2011 11:34 AM
  • Yes, this solves the basic problem of POST upload body.  I'd like to get the bimap into memory on the server rather than in a file for this experiment.  I'm using a single instance of the service rather than per call.  This is for experimental stage of development.  The following service works for moving a byte array to and from server.  How do I get the data into bitmap format?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Web;
    using System.Text;
    using System.IO;
    using System.Drawing;
    
    namespace WcfRestService1
    {
        // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page
        // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
        // a single instance of the service to process all calls.	
        [ServiceContract]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
        // NOTE: If the service is renamed, remember to update the global.asax.cs file
        public class Service1
        {
            List<SampleItem> itemList;
    
            [WebGet(UriTemplate = "")]
            public List<SampleItem> GetCollection()
            {
    
                if (itemList == null)
                {
                    itemList = new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Initializing new list... .", timeSent = DateTime.Now, bytes = null } };
                    return itemList;
                }
                else
                    return itemList;
            }
    
            [WebInvoke(UriTemplate = "", Method = "POST")]
            public string Create(Stream data)
            {
    
                if (itemList == null)
                {
                    itemList = new List<SampleItem>();
                }
    
                byte[] buffer = new byte[WebOperationContext.Current.IncomingRequest.ContentLength]; //32768
                MemoryStream ms = new MemoryStream();
                int bytesRead, totalBytesRead = 0;
                do
                {
                    bytesRead = data.Read(buffer, 0, buffer.Length);
                    totalBytesRead += bytesRead;
    
                    ms.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);
    
                SampleItem item = new SampleItem();
                //MemoryStream toBitmap = new MemoryStream(buffer);
                
                //Image image = Image.FromStream(toBitmap);
                //item.bmpImage = new Bitmap(image);
                if (itemList.Count == 0)
                    item.Id = 0;
                else
                    item.Id = itemList.Count + 1;
                item.bytes = buffer;
                item.timeSent = DateTime.Now;
                itemList.Add(item);
                return "Working image to bitmap GMD";
            }
    
            [WebGet(UriTemplate = "{id}")]
            public byte[] Get(string id)
            {
                if (itemList.Count>0)
                    return itemList[int.Parse(id)].bytes;
                else
                    return null;
            }
    
            [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
            public SampleItem Update(string id, SampleItem instance)
            {
                // TODO: Update the given instance of SampleItem in the collection
                throw new NotImplementedException();
            }
    
            [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
            public void Delete(string id)
            {
                // TODO: Remove the instance of SampleItem with the given id from the collection
                throw new NotImplementedException();
            }
    
        }
    }
    


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Monday, December 26, 2011 9:53 PM
  • Hi!

    I think the problem is in the following line:

    MemoryStream toBitmap = new MemoryStream(buffer);
    
    

    You create the MemoryStream from the buffer variable, but it is used only for reading data sent from the client:

     bytesRead = data.Read(buffer, 0, buffer.Length);
    
    

    Data coming from the client are written to the buffer variable always starting from position 0. In this way, if the data cannot be read in a single operation (i.e., bytesRead is less than buffer.Length, that is common when having large file transfers), there is a new read operation that overwrite the content of buffer variable. This is the reason why I have set the fixed dimension of 32768 (32 KB) for the buffer variable: it is used only as a temporary store.

    The "good" data are stored in the MemoryStream called ms. As a conseguence, you must replace the instruction

    MemoryStream toBitmap = new MemoryStream(buffer);
    
    

    With

    MemoryStream toBitmap = new MemoryStream(ms.ToArray());
    


    And, in the same way, the instruction

    item.bytes = buffer;
    


    With

    item.bytes = ms.ToArray();
    
    

    I hope this solves your problem!


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Tuesday, December 27, 2011 1:07 PM
  • Thanks for correcting my mistake.  Using Fiddler2 generated POST, the following code throws where indicated by the comment. But my own console app will create the bitmap file.  Console code follows the Web service code.

     

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Web;
    using System.Text;
    using System.IO;
    using System.Drawing;
    
    namespace WcfRestService1
    {
        // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page
        // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
        // a single instance of the service to process all calls.	
        [ServiceContract]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
        // NOTE: If the service is renamed, remember to update the global.asax.cs file
        public class Service1
        {
            // TODO: Implement the collection resource that will contain the SampleItem instances
            List<SampleItem> itemList;
    
            [WebGet(UriTemplate = "")]
            public List<SampleItem> GetCollection()
            {
                // TODO: Replace the current implementation to return a collection of SampleItem instances
                if (itemList == null)
                {
                    itemList = new List<SampleItem>() { new SampleItem() { Id = 0, StringValue = "Initializing new list... .", timeSent = DateTime.Now, bmpImage = null } };
                    return itemList;
                }
                else
                    return itemList;
            }
    
            [WebInvoke(UriTemplate = "", Method = "POST")]
            public string Create(Stream data)
            {
    
                if (itemList == null)
                {
                    itemList = new List<SampleItem>();
                }
    
                            
                byte[] buffer = new byte[32768]; //32768
                MemoryStream ms = new MemoryStream();
                int bytesRead, totalBytesRead = 0;
                
                do
                {
                    bytesRead = data.Read(buffer, 0, buffer.Length);
                    totalBytesRead += bytesRead;
    
                    ms.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);
    
                SampleItem item = new SampleItem();
                MemoryStream toImage = new MemoryStream(ms.ToArray());
                
                try
                {
                    Item image = Image.FromStream(toImage); //error here with Fiddler2 POST
                    item.bitmapImage = new Bitmap(image);
                
                    if (itemList.Count == 0)
                        item.Id = 0;
                    else
                        item.Id = itemList.Count + 1;
    
                
                    item.timeSent = DateTime.Now;
                    itemList.Add(item);
                    return "Working image to bitmap.";
                }
                catch(Exception ex )
                {
                    return "error: " + ex.Message ;
                }
                
                
            }
    
            [WebGet(UriTemplate = "{id}")]
            public Image Get(string id)
            {
                if (itemList.Count>0)
                    return itemList[int.Parse(id)].image;
                else
                    return null;
            }
    
            [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
            public SampleItem Update(string id, SampleItem instance)
            {
                // TODO: Update the given instance of SampleItem in the collection
                throw new NotImplementedException();
            }
    
            [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
            public void Delete(string id)
            {
                // TODO: Remove the instance of SampleItem with the given id from the collection
                throw new NotImplementedException();
            }
    
        }
    }
    

     

    Console application to send the POST. This works.

     

    using System;
    using System.Net;
    using System.IO;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                HttpWebRequest request =
                                 WebRequest.Create("http://localhost:33285/Service1/") as HttpWebRequest;
    
                request.Method = "POST";
    
                FileStream bmpFile = new FileStream(@"C:\bitmap\TestBitmap.bmp", FileMode.Open);
                
                BinaryReader reader = new BinaryReader(bmpFile);
                byte[] bytes = reader.ReadBytes((int)bmpFile.Length);
    
                request.ContentLength = bytes.Length;
                request.ContentType = "image/bmp";
    
                Stream requestStream = request.GetRequestStream();
    
                requestStream.Write(bytes, 0, bytes.Length);
    
                HttpWebResponse response;
                try
                {
                    response = request.GetResponse() as HttpWebResponse;
    
                    Console.WriteLine("Reaponse status code: " + response.StatusCode);
    
                    response.Close();
                }
                catch (Exception ex)
                {
                    string exception = ex.Message + " Inner:" + ex.InnerException;
                    Console.WriteLine(exception);
                    
                }
                
            }
        }
    }
    


    This posting is provided "AS IS" with no warranties, and confers no rights.





    • Edited by Mike Dodaro Wednesday, December 28, 2011 2:08 AM
    Tuesday, December 27, 2011 9:17 PM
  • Hi!

    Can you tell me the error message you obtain?

    Using the Fiddler2 generated POST, can you verify if the totalBytesRead variable is equals to the original dimension of the bitmap you're trying to transmit?


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Wednesday, December 28, 2011 12:29 PM
  • The error is "parameter is not valid".  The original file is 226K and totalBytesRead after POST is 230K.

     

    Also, when I try to retreive the bitmap using the following code, I sometimes get a server error, and looking at the bitmap in the debugger, all the properties throw errors. However, not all the saved bitmaps are like this.  Some show correct properties.  Very perplexing.

    This is not the case with the Create method on the POST.  There the debugger shows good bitmap when running my console POST.

     

     

            [WebGet(UriTemplate = "{id}")]
            public Image Get(string id)
            {
                try
                {
                    if (itemList.Count > 0)
                        return itemList[int.Parse(id)].bmpImage;
                    else
                        return null;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
    


    This posting is provided "AS IS" with no warranties, and confers no rights.

     


    • Edited by Mike Dodaro Wednesday, December 28, 2011 5:09 PM
    Wednesday, December 28, 2011 4:51 PM
  • It seems that there is some issue with Fiddler2 generated post.

    I have tried the code with a Windows Forms and a Windows Phone application and in both cases it works correctly. I have tried also to make REST call with RestSharp, http://restsharp.org/, and again it works as excepted.


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Thursday, December 29, 2011 12:12 PM
  • Thanks for sanity check.
    This posting is provided "AS IS" with no warranties, and confers no rights.
    Thursday, December 29, 2011 5:52 PM
  • You're welcome :-)
    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Thursday, December 29, 2011 7:41 PM
  • Ok, next sticking point is deserializing the data on the client.  No matter what kind of data type I send from the Web service, when I try to deserialize on the client, I get an error that says the Xml data has an error.
    Deserializing like this in several variations:
            protected void TextBox1_TextChanged(object sender, EventArgs e)
            {
                HttpWebRequest request =
                  WebRequest.Create("http://localhost:33285/Service1/" + int.Parse(TextBox1.Text)) as HttpWebRequest;
                
                HttpWebResponse response;
                request.Method = "GET";
    
                response = request.GetResponse() as HttpWebResponse;
    
                BinaryReader binaryReader = new BinaryReader(response.GetResponseStream());
    
                byte[] buffer = new byte[32768]; 
                MemoryStream ms = new MemoryStream();
                int bytesRead, totalBytesRead = 0;
    
                do
                {
                    bytesRead = binaryReader.Read(buffer, 0, buffer.Length);
                    totalBytesRead += bytesRead;
    
                    ms.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);
    
    
                using (XmlTextReader reader = XmlTextReader.Create(ms) as XmlTextReader)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(Bitmap));
                    Bitmap bitmap= (Bitmap)serializer.Deserialize(reader);
                    bitmap.Save(Server.MapPath("/FileData/bitmap" + TextBox1.Text + ".bmp"));
                    
                }
    
                Image1.ImageUrl = Server.MapPath("/FileData/bitmap" + TextBox1.Text + ".bmp";
    
    Server method looks like this:
    [WebGet(UriTemplate = "{id}")]
            public Bitmap Get(string id)
            {
                try
                {
                    if (itemList.Count > 0)
                    {
                        MemoryStream stream = new MemoryStream(itemList[int.Parse(id)].BitmapData);
                        
                        return new Bitmap(stream);
                                            
                    }
                    else
                        return null;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }

    This posting is provided "AS IS" with no warranties, and confers no rights.



    • Edited by Mike Dodaro Friday, December 30, 2011 7:45 AM
    Friday, December 30, 2011 2:06 AM
  • Hi!

    Try returning a Stream with Bitmap bytes from the server:

    [WebGet(UriTemplate = "{id}", BodyStyle = WebMessageBodyStyle.Bare)]
    public Stream Get(string id)
    {
            try
            {
                if (itemList.Count > 0)
                {
                    MemoryStream stream = new MemoryStream(itemList[int.Parse(id)].BitmapData);                    
                    return stream;                                        
                }
                else
                    return null;
            }
            catch (Exception ex)
            {
                return null;
            }
    }
    

    Then, on the client, you can write something like this:

    private void btnGetFile_Click(object sender, EventArgs e)
    {
        string uri = string.Format("{0}photos", BASE_ADDRESS);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri + "/12");
    
        // Get response  
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            pictureBox1.Image = System.Drawing.Image.FromStream(response.GetResponseStream());
        }
    }
    

    This works correctly for me.


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    • Marked as answer by Mike Dodaro Friday, December 30, 2011 3:19 PM
    Friday, December 30, 2011 11:48 AM
  • Very concise and elegant.  Thanks, Marco!  Working now: http://wp.me/p1TEdE-df
    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Edited by Mike Dodaro Saturday, December 31, 2011 12:44 AM
    Friday, December 30, 2011 3:22 PM
  • I'm happy to know that my solution has solved your problem!


    Marco Minerva [MCPD], http://blogs.ugidotnet.org/marcom
    Friday, December 30, 2011 4:12 PM