而序列化Stream对象的Web API控制器方法,给人异常 [英] Web api controller method giving exception while serializing the Stream object

查看:975
本文介绍了而序列化Stream对象的Web API控制器方法,给人异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API控制器的方法如下:

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);
}

我打电话从Java小程序此方法的网址为:

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

http://localhost1/api/PostMethod/1

我得到了3号线的异常说法为:

I get an exception in line number 3 saying as:

超时不支持此流,在'ObjectContent`1 类型未能响应主体的内容类型应用/ JSON序列化;  字符集= UTF-8'。

"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'."

可能是什么这个可能的解决方案?如何通过的WebAPI控制器方法,JSON对象发送流?

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

推荐答案

网络API支持内容协商,则不需要序列化对象只返回了。

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

网络API将自动返回XML或JSON的客户端

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

content-type: application/json

Web浏览器通常会得到XML,而作为JavaScript的JSON。您的Java小程序只需要上面的标题(它实际上看起来像它可能已发送)。

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();
}

这很大程度上取决于什么downloadStream方法返回;

This depends a lot on what the downloadStream method returns;

这篇关于而序列化Stream对象的Web API控制器方法,给人异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆