我正在尝试返回一个大的集合json(大约2MB)但web api返回错误:
“使用JSON JavaScriptSerializer进行序列化或反序列化时出错。字符串的长度超过了maxJsonLength属性上设置的值”。我已经尝试在web.config中配置maxJsonLength属性但没有成功。
我在stackoverflow中看到了另一个answers,但都与常规.NET MVC控制器有关,而不是ApiController。
可以绕过内部JavaScriptSerializer maxJsonLenght或者做一些自定义的JsonSerializerType格式吗?
答案 0 :(得分:1)
根据JSON有效负载的大小,您可能必须流式传输响应。见this blog post。简而言之,博客文章可以通过以下代码进行总结:
[HttpGet]
public HttpResponseMessage PushStreamContent()
{
var response = Request.CreateResponse();
response.Content =
new PushStreamContent((stream, content, context) =>
{
foreach (var staffMember in _staffMembers)
{
var serializer = new JsonSerializer();
using (var writer = new StreamWriter(stream))
{
serializer.Serialize(writer, staffMember);
stream.Flush();
}
}
});
return response;
}
答案 1 :(得分:0)
您是否尝试过设置web.config中的MaxJsonDeserializerMembers?
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
答案 2 :(得分:0)
感谢@BMac的帮助,你引导我找到一个有效的解决方案。
[HttpGet]
//ResponseType it's for ApiDescription successfully generates the helper page with the right type since i'm returning a plain/text content
[ResponseType(typeof(YourType))]
public async Task<HttpResponseMessage> GetLargeJsonDataWithWebAPI()
{
String url = "someUrl";
String jsonData = EnvironmentUrlHelper.GetJsonResourseAsync<YourType>(url);
var response = Request.CreateResponse();
response.Content = new StringContent(JsonConvert.SerializeObject(rsp));
return response;
}