4

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?

Betty
  • 9,109
  • 2
  • 34
  • 48
user1400915
  • 1,933
  • 6
  • 29
  • 55

1 Answers1

2

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;

Betty
  • 9,109
  • 2
  • 34
  • 48
  • 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? – user1400915 Oct 13 '12 at 02:51
  • 2
    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. – Betty Oct 13 '12 at 03:17
  • 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 – user1400915 Oct 13 '12 at 03:27
  • what exactly does service.downloadstream do? – Betty Oct 13 '12 at 03:56
  • 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? – user1400915 Oct 13 '12 at 03:59