0

我有一个方法,它是在线ExecuteResult上抛出一个。发生这种情况是因为对象在内存中对于;来说太大了。它填满了记忆。System.OutOfMemoryExceptionResponse.Write(sw.ToString())StringWriterToString

我一直在寻找解决方案,但似乎找不到一个简单干净的解决方案。任何想法将不胜感激。

代码:

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

1 回答 1

1

我认为问题在于您将所有 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);
}
于 2015-11-09T02:54:11.050 回答