2016-04-20 40 views
0

我知道這個問題已被多次詢問,並且我已經搜索了這些問題的解決方案,以解決我的代碼無法解決的問題。所以在這裏。試圖解決錯誤: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. 
} 

莫名其妙的是我如果有人能指出我做錯了什麼,我將不勝感激。

回答

0

好的,這個問題困擾了我很長一段時間,直到我偶然發現了一個解決方案。

對於你們中的任何一個有類似的問題,這是最終爲我工作的。

我從在Page_Load()事件刪除ScriptManager.GetCurrent(this).RegisterPostBackControl(btnPayrollDetails);並把它添加到button_Init事件:

<asp:Button ID="btnPayrollDetails" runat="server" Text="Payroll Details" OnClick="btnPayrollDetails_Click" OnInit="btnPayrollDetails_Init" /> 

protected void btnPayrollDetails_Init(object sender, EventArgs e) 
{ 
    ScriptManager.GetCurrent(this).RegisterPostBackControl(btnPayrollDetails); 
} 

出於某種原因,該按鈕沒有得到註冊腳本管理器,它從pageLoad的移動()到按鈕Init()方法修復了這個問題。

相關問題