【发布时间】: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
如何避免这种情况?
【问题讨论】:
-
缩短?我们到底在谈论多大? (最小/平均/最大)
-
将部分字符串直接写入响应中,如stackoverflow.com/a/62929137/1479335
-
避免将大型请求体或响应体读入内存。如何保持避免它!如果我想读取一个大文件内容,对内容做一些业务逻辑,并在 web api 中将 json 结果作为字符串返回。在客户端,javascript 将处理 json 结果。
-
您能在
stub.cs中显示更多代码吗?它是否读取文件然后返回字符串?
标签: c# asp.net asp.net-core asp.net-web-api stringbuilder