簡體   English   中英

將大型JSON數據從C#Web API發送到Javascript客戶端

[英]Sending large JSON data from C# Web API to Javascript Client

我對服務器的調用是按以下方式構建的:

  • 我在客戶端上有一個callServer函數,它將數據發送到我的API;
  • 然后我的API從它的控制器接收數據並將其傳遞給一個調用DB的函數;
  • 控制器將響應發送回客戶端。

我就是這樣做的(這些只是代碼的重要部分,而不是一切都在這里):

API(Context.cs):

public static IEnumerable<Dictionary<string, object>> Proc_example(int? value)
    {
        using (NpgsqlConnection conn = new NpgsqlConnection(ConnStr))
        {
            try
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "proc_example";
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.Add(new NpgsqlParameter("value", convertNullValue(value)));

                    var reader = cmd.ExecuteReader();
                    return new DrToDictionary().Serialize(reader);

                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                conn.Close();
            }
        }
    }

API(Controller.cs):

[Authorize]

    public JsonResult example(int? value)
    {
        try
        {
            var data = Context.Proc_example(value);

            return Json(new AppServerResult()
            {
                Result = new { list = data }
            }, JsonRequestBehavior.AllowGet);


        }
        catch (Exception e)
        {
            return Json(new AppServerResult()
            {
                HasError = true,
                ErrorMessage = "Houve um erro ao consultar, tente novamente."

            });
        }
    }

客戶端(callServer):

app.callServer = function (options, sucessCallback, httpErrCallback, serverErrCallback, operationErrorCallback) {
if (options.source == undefined)
    options.headers = { "Authorization": $.cookie('Token') }

options.success = function (result) {
    try {
        var _result = result;

        if (typeof _result == "string") {
            _result = jQuery.parseJSON(_result);
        }

        if (typeof _result.HasError != "undefined" && _result.HasError) {

            if (!_result.IsValidationError) {
                if (typeof __apiCallerErrorCallback == "function") 
                    __apiCallerErrorCallback(_result.ErrorMessage);

                if (typeof serverErrCallback == "function") {
                    serverErrCallback(_result.ErrorMessage);
                }
            } else {
                app.notifyValidationException(_result.ErrorMessage);                   
            }

        } else {

            if (typeof sucessCallback == "function") {
                if (_result.Result != undefined) sucessCallback(_result.Result);
                else sucessCallback(_result);
            }
        }
    } catch (ex) {

        throw ex;

    }
};

options.error = function (result) {

    if (typeof httpErrCallback == "function") {
        httpErrCallback();
        }
    if (typeof __apiCallerErrorCallback == "function")
        __apiCallerErrorCallback("HTTP Error");
    }

};

jQuery.ajax(options);

};

調用示例:

callingTheServerExample = function (callback, value) {
app.callServer({
    type: "POST",
    url: app.webAPIRootPath + "Controller/example",
    data: "{ 'value':" + JSON.stringify(ko.toJS(value)) + " }",
    contentType: "application/json; charset=utf-8",
    dataType: "json"
}, function (result) {
    if (typeof callback == "function")
        callback(result);
});
}

我的問題是當我的JSON太大時,我的API在將數據發送回客戶端時會給我一個JsonMaxLength異常(異常發生在控制器類上)。 我不想將maxJsonLength設置為更高的值。 相反,我想找到一種方法從API發送我的JSON,並通過javascript將其掛載到客戶端。

有辦法嗎?

編輯:

我忘了添加一個細節:我正在使用REST API。 如下面的評論中所述,分頁是一種解決方案,但我需要的是讓整個記錄集立即可用。 可以使用分頁來實現它,但它似乎更慢並且會導致更多的API調用。 流式傳輸似乎是一種解決方案,但我以前從未這樣做,我無法弄清楚如何實現它。

編輯2:

我已經像這樣實現了我的分頁:

         public JsonResult example(int? value, int page)
    {
        try
        {
            var data = Context.Proc_example(value, page);

            if (pPage > 0)
            {
                var pagedResult = data.Skip((page - 1) * 20).Take(20).ToList();

                return Json(new AppServerResult()
                {
                    Result = new { list = data}
                }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new AppServerResult()
                {
                    Result = new { list = data}
                }, JsonRequestBehavior.AllowGet);
            }

        }
        catch (Exception e)
        {
            return Json(new AppServerResult()
            {
                HasError = true,
                ErrorMessage = "Houve um erro ao consultar, tente novamente."

            });
        }
    }

但我仍然沒有實現我想要的。 有人會想到一個更好的方法嗎?

對於JsonMaxLength例外

嘗試

寫在web.config中

<system.web.extensions>
<scripting>
  <webServices>
    <jsonSerialization maxJsonLength="1000000">
    </jsonSerialization>
  </webServices>
</scripting>
</system.web.extensions>

默認情況下,maxJsonLength為102400。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM