类型的异常' System.OutOfMemoryException'被抛出的WEB API

时间:2016-08-03 00:08:32

标签: asp.net json asp.net-mvc asp.net-web-api

我们创建了用于查询Oracle DB的Web API,以下面的格式返回JSON中的结果。因此,API将获取输入参数数组。由于查询结果非常庞大,就像下面的查询一样,当我们尝试使用SQL Developer时,它会返回313568。

来自STCD_PRIO_CATEGORY的SELECT *,其中STPR_STUDY.STD_REF IN(" BL001,TM002")

以下是我们正在使用的代码

public HttpResponseMessage Getdetails([FromUri] string[] id)
{
   string connStr = ConfigurationManager.ConnectionStrings["ProDataConnection"].ConnectionString;
    using (OracleConnection dbconn = new OracleConnection(connStr))
    {
        var inconditions = id.Distinct().ToArray();
        var srtcon = string.Join(",", inconditions);
        DataSet userDataset = new DataSet();
        var strQuery = @"SELECT * from STCD_PRIO_CATEGORY where STPR_STUDY.STD_REF IN(" + srtcon + ")";
        using (OracleCommand selectCommand = new OracleCommand(strQuery, dbconn))
        {
            using (OracleDataAdapter adapter = new OracleDataAdapter(selectCommand))
            {
                DataTable selectResults = new DataTable();
                adapter.Fill(selectResults);
                var returnObject = new { data = selectResults };
                var response = Request.CreateResponse(HttpStatusCode.OK, returnObject, MediaTypeHeaderValue.Parse("application/json"));
                ContentDispositionHeaderValue contentDisposition = null;
                if (ContentDispositionHeaderValue.TryParse("inline; filename=ProvantisStudyData.json", out contentDisposition))
                {
                    response.Content.Headers.ContentDisposition = contentDisposition;
                }
                return response;

当我使用网址https://bhbl.abc.org/api/Sample?id=' BL001'& id =' TM002'  查询数据库为 enter image description here

但是当我使用网址https://bhbl.abc.org/api/Sample?id=' BL001'它返回的结果只有41552条记录

如何创建将返回大量数据的API。非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

这是因为,api返回的数据太大,进程产生内存溢出。您需要使用分页sql:

SELECT *
  FROM (SELECT a.*, ROWNUM rn
          FROM (SELECT *
                  FROM table_name) a
         WHERE ROWNUM <= 40)
 WHERE rn >= 21

客户端处理一次,多次调用api,完成所有数据获取。

以下客户核心代码:

// ids: 'BL001' 'TM002', next_key: paging record index
while (next_key != null)
{
    next_key = GetDetails(ids, next_key);
}

private string GetDetails(stirng[] ids, string next_key)
{
    // call api
    var result = ...;

    // parse api reponse result
    object key = result.next_key;
    if (key == null) return null;
    string s = key.ToString();
    return string.IsNullOrEmpty(s) ? null : s;
}

下面的服务器核心代码:

public HttpResponseMessage Getdetails([FromUri] string[] id, [FromUri] string next_key)
{
    // use paging sql
    // excute sql return record count
    var count = ...

    // return next_key
    if (count < 20)
    {
        result.next_key = null;
    }
    else
    {
        result.next_key = (int.Parse(next_key) + 20).ToString();
    }

    return result;
}