【问题标题】:StringWriter memory out of bounds exceptionStringWriter 内存越界异常
【发布时间】: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


    【解决方案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);
    }
    

    【讨论】:

    • 这似乎已经解决了服务器端内存不足异常,谢谢!现在我需要找出为什么它会抛出 Json 内存不足错误。
    • 错误是这样的:0x8007000e - JavaScript 运行时错误:没有足够的存储空间来完成此操作。奇怪的是,它有时第一次出现在页面上。之所以提到这一点,是因为您可能也对那里发生的事情有一个快速的了解。无论哪种方式,您都解决了我的服务器端问题,因此将您标记为答案。
    • 听起来是一个不同但相关的问题。我建议为此打开一个新问题,它会显示您的客户端代码并指示您尝试发送多少数据。
    • 是的,使用 chrome 似乎可以解决这个问题,所以我将单独调查,再次感谢。
    • 没问题;很高兴我能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 2018-06-07
    • 2013-11-28
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多