Web api controller method giving exception while serializing the Stream object

12,307

Web Api supports content negotiation, you don't need to serialize the object just return it.

Web Api will automatically return XML or Json to the client depending on what they ask for

content-type: application/json

Web Browsers will typically get XML, while as javascript Json. Your java applet just need the header above (which it actually looks like it might be sending already).

[HttpPost]
public string PostMethod(int id)
{
   Stream downloadStream = Service.downloadStream(id);  
   System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
   downloadStream.CopyTo(memoryStream);
   return memoryStream.ToString();
}

This depends a lot on what the downloadStream method returns;

Share:
12,307
user1400915
Author by

user1400915

Updated on June 27, 2022

Comments

  • user1400915
    user1400915 about 2 years

    I have a web api controller method as follows:

    [HttpPost]
    public string PostMethod(int id)
    {
      Stream downloadStream = Service.downloadStream(id);  
      JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
      string output  = jsonSerializer.Serialize(downloadStream);
    }
    

    I am calling this method from java applet with url as:

    http://localhost1/api/PostMethod/1
    

    I get an exception in line number 3 saying as:

    "timeouts are not supported on this stream,The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."

    What could be the possible solution for this?How to send the stream through Webapi controller method as JSON object?

  • user1400915
    user1400915 over 11 years
    Ok but I tested it from fiddler. I got exception as downloadStream.ReadTimeout' threw an exception of type 'System.InvalidOperationException' and a inner exception ",The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'" .My concern is why the stream object is not getting serialised?Is there any way to avoid the ReadTimeout exception?
  • Betty
    Betty over 11 years
    A stream is an open file or network connection, it doesn't make sense to serialize it. The contents from it yes, but the stream itself no.
  • user1400915
    user1400915 over 11 years
    Thanks ,is there any way to avoid the ReadTimeout exception ?One more thing ,then how I would return the stream object?public stream PostMethod(int id) { return stream ;} will anyways give me exception
  • Betty
    Betty over 11 years
    what exactly does service.downloadstream do?
  • user1400915
    user1400915 over 11 years
    I am storing the file in streams in SQL server.So,service.downloadstream returns that stream to applet for consumption. My only problem is applet is getting 500 Internal error saying "Object failed to serialize".Any alternative or solution?