我知道這個問題已被多次詢問,並且我已經搜索了這些問題的解決方案,以解決我的代碼無法解決的問題。所以在這裏。試圖解決錯誤:HTTP標頭髮送後,服務器無法設置內容類型
我有一個更新面板的頁面。在此更新面板上,我有一個生成Telerik pdf報告並下載它的按鈕。但是,當點擊按鈕時,我得到了臭名昭着的錯誤:服務器無法在發送HTTP頭後設置內容類型。
這裏是我的代碼(簡化爲便於發佈這樣一個問題:
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(this).RegisterPostBackControl(btnPayrollDetails);
}
protected void btnPayrollDetails_Click(object sender, EventArgs e)
{
PayPeriod pay = GetPeriod();
if (pay == null || (pay.Expenses.Count == 0 && pay.Invoices.Count == 0))
{
return;
}
var file = "test";
var report = new Core.Reports.PayrollDetails(Global.Account.Member.ID, pay, mypMonth.SelectedDate.Value);
Telerik.Reporting.Processing.RenderingResult result = new Telerik.Reporting.Processing.ReportProcessor().RenderReport("PDF", report, null);
this.Response.DownloadFile(result.DocumentBytes, file + ".pdf");
}
到this.Response.DownloadFile調用調用擴展方法在這裏:
public static void DownloadFile(this HttpResponse Response, byte[] fileBytes, string fileName, string mime = "application/pdf")
{
Response.Clear();
Response.BufferOutput = true;
Response.ContentType = mime;
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
using (MemoryStream ms = new MemoryStream(fileBytes)) { ms.WriteTo(Response.OutputStream); }
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
}
莫名其妙的是我如果有人能指出我做錯了什麼,我將不勝感激。