2015-01-22 13 views
0

다음 오류가 발생합니다. HTTP 헤더를 보낸 후 서버에서 컨텐츠 유형을 설정할 수 없습니다. 나는이 오류와 함께 SO 질문을 포함하여 온라인에서 둘러 보았지만 아무도 내 문제를 해결하지 못했습니다. 여기에 내 특별한 시나리오가 있습니다 :HTTP 헤더를 보낸 후 서버에서 컨텐츠 유형을 설정할 수 없습니다. - 업데이트 패널 내의 오류 후

나는 modalpopupextender 내부에있을 수있는 업데이트 패널 내부에있는 asp.net gridview 있습니다. gridview에는 imagebutton이있는 템플릿 필드가 있으며 클릭하면 PDF가 다운로드됩니다. 다운로드를 시도하는 중에 오류가 발생할 때까지 모든 것이 잘 작동합니다. Gridview.RowCommand 이벤트 내부의 오류를 처리하고 원하는대로 페이지가 클라이언트에서 다시 변경되지 않습니다. 그러나 다운로드를 다시 클릭하면 파일이 다운로드되지 않고 ScriptManager.AsyncPostBackError 이벤트에서 오류가 발생합니다. "HTTP 헤더를 보낸 후에 서버에서 콘텐츠 형식을 설정할 수 없습니다." 미리 감사드립니다!

--Default.aspx--

<asp:HiddenField ID="hdnHiddenField" runat="server" /> 
<cc1:ModalPopupExtender ID="hdnHiddenField_mpeModalPopup" runat="server" Enabled="True" TargetControlID="hdnHiddenField" 
    CancelControlID="lnkClose" PopupControlID="pnlPanel" BackgroundCssClass="modalBackground"></cc1:ModalPopupExtender> 
<asp:Panel ID="pnlPanel" runat="server" BorderStyle="Double" Width="50%" Height="75%" CssClass="modalPopup" style="overflow: auto; display: none"> 
    <div class="modalHeaderClose"> 
     <asp:LinkButton ID="lnkClose" runat="server" Text="Close [X]"></asp:LinkButton> 
    </div> 
    <cc1:Accordion ID="accdnPolicyInfo" runat="server" SelectedIndex="0" RequireOpenedPane="false"> 
     <Panes> 
      <cc1:AccordionPane ID="accpnlDocuments" runat="server"> 
       <Header> 
        <div class="accordionHeader">Documents</div> 
       </Header> 
       <Content> 
        <asp:UpdatePanel ID="upDocuments" runat="server" UpdateMode="Conditional"> 
         <ContentTemplate> 
          <div style="text-align: center; padding: 0 10px 10px 10px;"> 
           <asp:GridView ID="gvGridView" runat="server" AutoGenerateColumns="False" Width="100%" ShowHeaderWhenEmpty="True"> 
            <Columns>          
             <asp:TemplateField> 
              <ItemTemplate> 
               <asp:ImageButton ID="imgDownloadPDF" runat="server" 
                CommandArgument='<%# Bind("ImageKey") %>' CommandName="DownloadDocument" 
                ImageUrl="~/images/PDF-download.png" ToolTip="Download file to your computer" /> 
              </ItemTemplate> 
             </asp:TemplateField> 
            </Columns> 
            <EmptyDataRowStyle ForeColor="Red" HorizontalAlign="Center" /> 
           </asp:GridView> 
          </div> 
         </ContentTemplate> 
        </asp:UpdatePanel> 
       </Content> 
      </cc1:AccordionPane> 
     </Panes>     
    </cc1:Accordion>    
</asp:Panel> 

--Default.aspx.vb--

Private Sub gvPolicyDocs_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPolicyDocs.RowDataBound 
    Dim imgDownloadPDF As ImageButton = e.Row.FindControl("imgDownloadPDF") 
    If imgDownloadPDF IsNot Nothing Then 
     ScriptManager.GetCurrent(Page).RegisterPostBackControl(imgDownloadPDF) 
     'I just tried changing to RegisterAsyncPostBackControl method and found that I receive the same error even on the first attempt 
    End If 
End Sub 

Protected Sub gvPolicyDocs_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvPolicyDocs.RowCommand 
    Try 
     StreamPDF(e.CommandArgument, False) 
    Catch ex As Exception 
     ErrorHandler.HandleError(ex) 'sends out an email and returns back; ErrorHandler is an object I created 
    End Try 
    hdnHiddenField_mpeModalPopup.Show() 'otherwise modal popup disappears after return from postback 
End Sub 

Private Sub StreamPDF(ByVal strImageKey As String) 
    Dim dtImagePaths As DataTable 
    Dim oPDFManager As New PdfManager 'from ASPPDF library 
    Dim bytes() As Byte 
    Dim strImagePath As String = String.Empty 

    If String.IsNullOrEmpty(strImageKey) Then 
     Throw New Exception("Invalid Image Key") 
    End If 

    'Get image path from database 
    ... 
    ... 

    strImagePath = dtImagePaths.Rows(0).Item("ImagePath") 
    bytes = oPDFManager.OpenDocument(strImagePath).SaveToMemory() 
    'I checked that on the run after the error, bytes contains exactly what I want - so when I write it to a file locally, I can see the PDF 

    With Current 
     .Response.BufferOutput = False 'tried true and false 
     .Response.Clear() 
     .Response.ClearContent() 
     .Response.ClearHeaders() 
     .Response.ContentType = "application/pdf" 
     .Response.AddHeader("Content-Disposition", String.Format("{0}; filename={1}.pdf", IIf(bDownloadFile, "attachment", "inline"), strImageKey)) 
     .Response.AddHeader("Content-Length", bytes.Length) 
     .Response.BinaryWrite(bytes) 
     .Response.Flush() 
     .Response.Close() 
     'Response.End()  '--> See http://support.microsoft.com/kb/312629 
     .ApplicationInstance.CompleteRequest() 
    End With 
End Sub 

답변

1

UpdatePanel 아마 여기에 문제가 : 여기

내 코드입니다 .

여기를 참조하십시오. 글쎄, 경우에 다른 사람이이 문제에 실행

Why won't Response.Write() export a CSV file to the browser?

+0

알겠습니다. 그리고 이미 전체 포스트 백을 수행하도록 이미지 단추를 설정했습니다. 그리고 오류가 발생하지 않으면 항상 작동합니다. 문제는 다음 요청에서 오류가 발생하는 이유는 무엇이며 어떻게 업데이트 패널을 유지하면서 문제를 해결할 수 있습니까? – user1422348

0

this article 완전히 나를 도왔다. 기본적으로 동일한 페이지에서 UpdatePanel을 통해 asyncpostback 기능을 다운로드하여 사용할 수 없음을 나타냅니다. 모든 다운로드 코드가 완전히 다른 페이지에서 수행되고 해당 페이지가 현재 페이지의 숨겨진 iframe에서 열리는 해결 방법을 보여줍니다. 참고로, 새 창에서 pdf를 열려고하는 경우에도 동일한 해결 방법이 적용되지만 iframe을 현재 페이지에 추가하는 대신 JavaScript에서 window.open()을 호출 할 수 있습니다.

0

그래서이 문제를 VB에서 해결할 수 있을지 모르겠지만 C#에서이 문제의 원인을 알고 있습니다.이 문제는 직접이 문제를 해결해야했습니다.

문제는 버튼 자체에 있습니다. ScriptManager에 단추를 등록해야합니다. PageLoad() 이벤트에서이 작업을 수행 할 수 없으면 실제로 버튼에 OnInit 이벤트를 추가하고 거기에 등록을 추가해야합니다. C#에서

예 :

ASP 페이지 코드 :

<asp:ImageButton ID="imgDownloadPDF" runat="server" onInit="imgDownloadPDF_Init" ... /> 

코드 뒤에 :

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

도움이 되었기를 바랍니다.