我有一个方法ExecuteResult,它在行Response.Write(sw.ToString())中抛出一个System.OutOfMemoryException。之所以发生这种情况,是因为StringWriter对象对ToString来说内存太大;它填满了内存。
我一直在寻找一个解决方案,但似乎找不到一个简单、干净的解决方案。任何想法都将不胜感激。
代码:
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());
}
}
}
}发布于 2015-11-09 02:54:11
我认为问题在于,您正在将所有JSON缓冲到一个StringWriter中,然后尝试将它写成一个大块,而不是流到响应中。
尝试替换以下代码:
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
//outofmemory exception is happening here
response.Write(sw.ToString());
}在这方面:
using (StreamWriter sw = new StreamWriter(response.OutputStream, ContentEncoding))
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
scriptSerializer.Serialize(jtw, this.Data);
}https://stackoverflow.com/questions/33601609
复制相似问题