【发布时间】:2015-11-09 02:30:04
【问题描述】:
我有一个方法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());
}
}
}
}
【问题讨论】:
标签: asp.net-mvc json.net out-of-memory stringwriter