zoukankan      html  css  js  c++  java
  • Context.Response.End(); VS HttpContext.Current.ApplicationInstance.CompleteRequest();

    今天遇到一個問題,頁面Client端send一個ajax請求,然後在server端返回一個json的字符串

            $.ajax({
                    url: "xxxxx.aspx",
                    type: "post",
                    data: { action: "xxx", Id: $('#hiddenId').val(), fileKey: $('.hiddenFileKey').val(), tableName: selectedTableName }
                })
                .done(function (data) {
                    processResponse(data, false);
                })
                .fail(function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                });            

    功能很簡單,可是因為 Context.Response.End(); 的一慣壞名聲(強制返回),在server端不能使用,於是只能改為使用HttpContext.Current.ApplicationInstance.CompleteRequest(); 本來也沒有什麼問題。

                        Context.Response.Clear();
                        Context.Response.ContentType = "application/json";
                        Context.Response.AddHeader("content-length", ResponseJsonStr.Length.ToString());
                        Context.Response.Write(ResponseJsonStr);//Context.Response.End();
                        ApplicationInstance.CompleteRequest();
                        return;               

    就是上面的代碼,卻出現了一個奇怪的問題(目前為止不清楚問題的原因,同樣的代碼在其他頁面可以正常使用),返回到client頁面的json string除了json data的部分之外,還包含了整個頁面的html source code. 導致json parse時出現error

    JSON.parse: unexpected non-whitespace character after JSON data

    無奈之下,去網上尋求解決辦法,發現解法都是要使用 Context.Response.End();。TT

    終於在查看關於Context.Response的文檔時發現一個property: SuppressContent,可以控制內容是否回傳client 端。

    於是將server端代碼改為

                        Context.Response.Clear();
                        Context.Response.ContentType = "application/json";
                        Context.Response.AddHeader("content-length", ResponseJsonStr.Length.ToString());
                        Context.Response.Write(ResponseJsonStr);
                        Context.Response.Flush(); // Sends all currently buffered output to the client.
                        //Context.Response.End();
                        Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
                        ApplicationInstance.CompleteRequest();
                        return;

    問題解決。

  • 相关阅读:
    AtCoder Grand Contest 030题解
    Codeforces Round #542 (Div. 1) 题解
    ZJOI2019赛季回顾
    UOJ #450「集训队作业2018」复读机
    「IOI2018」狼人
    APIO2019游记
    BZOJ4314 倍数?倍数!
    伯努利数学习笔记&&Luogu P3711 仓鼠的数学题
    Codeforces Round #541 (Div. 2)题解
    UOJ #460 新年的拯救计划
  • 原文地址:https://www.cnblogs.com/sipher/p/8560064.html
Copyright © 2011-2022 走看看