【问题标题】:web api return too long string result outofmemoryweb api返回太长的字符串结果内存不足
【发布时间】:2021-07-07 08:30:28
【问题描述】:

我有一个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

如何避免这种情况?

【问题讨论】:

标签: c# asp.net asp.net-core asp.net-web-api stringbuilder


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 2013-04-04
    • 2016-05-28
    • 2011-08-13
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多