Context.Response.End(); VS HttpContext.Current.ApplicationInstance.CompleteRequest();

时间:2022-10-13 19:43:21

今天遇到一個問題,頁面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;

問題解決。