[英]StringWriter memory out of bounds exception
I have a method ExecuteResult
, which is throwing a System.OutOfMemoryException
at the line Response.Write(sw.ToString())
. 我有一个
ExecuteResult
方法,该方法在Response.Write(sw.ToString())
行抛出System.OutOfMemoryException
。 This is happening because the StringWriter
object is too large in memory for the ToString
; 这是因为
StringWriter
对象的内存对于ToString
太大; it fills up the memory. 它会填满内存。
I've been looking around for a solution but can't seem to find a simple clean solution to the problem. 我一直在寻找解决方案,但似乎无法找到解决问题的简单方法。 Any ideas would be greatly appreciated.
任何想法将不胜感激。
Code: 码:
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (this.Data != null)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
var scriptSerializer = JsonSerializer.Create(this.Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
//outofmemory exception is happening here
response.Write(sw.ToString());
}
}
}
}
I think the problem is you are buffering all of the JSON into a StringWriter and then trying to write it out in one big chunk instead of streaming it out to the response. 我认为问题在于您正在将所有JSON缓冲到StringWriter中,然后尝试将其大写写入而不是将其流式传输到响应中。
Try replacing this code: 尝试替换此代码:
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
//outofmemory exception is happening here
response.Write(sw.ToString());
}
With this: 有了这个:
using (StreamWriter sw = new StreamWriter(response.OutputStream, ContentEncoding))
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
scriptSerializer.Serialize(jtw, this.Data);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.