0

私はメソッドを持っています。これは行にExecuteResulta を投げています。これは、オブジェクトが;に対してメモリ内で大きすぎるために発生しています。それはメモリをいっぱいにします。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 にバッファリングしてから、応答にストリーミングするのではなく、1 つの大きなチャンクに書き出そうとしていることだと思います。

このコードを置き換えてみてください:

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 に答える