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;

    問題解決。

  • 相关阅读:
    java乱码问题解决
    发送邮件工具方法
    MD5加密算法工具类
    2015年4月与5月
    Hark的数据结构与算法练习之煎饼排序
    Hark的数据结构与算法练习之图书馆排序
    Hark的数据结构与算法练习之耐心排序
    Hark的数据结构与算法练习之多路归并排序
    Hark的数据结构与算法练习之若领图排序ProxymapSort
    启动mysql出现了error the server quit without updating pid file (/var/lib/mysql/localhost.localdomain.pid)
  • 原文地址:https://www.cnblogs.com/sipher/p/8560064.html
Copyright © 2011-2022 走看看