web api返回太长的字符串结果outofmemory

问题描述

我有一个asp.net web api,结果字符串很长,有时会发生内存不足异常。如何避免!

在 controller.cs 中

 // GET: /XXXX/DetailJson/5
 private ActionResult DetailJson()
 {
     //some times the ret string is too much long,out of memory exception will raise,string ret=stub.getResultString();
     return Content(ret,"text/plain",System.Text.Encoding.UTF8);
 }

在 stub.cs 中

 String getResultString()
 {
    StringBuilder ret="";
    ..........
    //sometimes the ret is very big,has very long length System.OutOfMemoryException will raise  !!!!
    return ret.ToString();
 }

[OutOfMemoryException:触发类型“System.OutOfMemoryException” 例外] System.Text.StringBuilder.ToString() +36

如何避免这种情况?

解决方法

尝试使用以下代码读取您的 .txt 文件。我可以成功读取它,但它无法响应浏览器,因为读取file.txt使用了5分钟以上。

enter image description here

public string getResultString()
{
    StringBuilder ret = new StringBuilder();
    //file in disk
    var FileUrl = @"E:\WebApplication1\file.txt";
    try
    {
        using (StreamReader sr = new StreamReader(FileUrl))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                ret.Append(line);
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("The file could not be read:");
        Console.WriteLine(e.Message);
    }
    return ret.ToString();
}