2011-10-18 29 views
0

我需要開始從寧靜的WCF服務文件下載,與和正在運行到的幾個問題。服務從寧靜的WCF可下載文件調用

如果我將我的安靜呼叫設置爲GET(GET調用與下面的參數相同,參數已移除並且名稱已更改),我可以將瀏覽器指向它,並獲得具有正確響應的方法,我的瀏覽器會提示我要下載的文件,在收到文件時,但它是空的,我的頭都顯示爲0的內容長度作爲一個說明通過服務調用步進,流是正確的。

如果我設置爲POST並使用JQuery將其作爲ajax調用(這是我希望的最終結果,因爲我需要將某些數據傳遞給服務,如有必要,我可以將數據點傳遞給網址並使用GET)。

我的問題:

  1. 我思念的東西返回過的WebHttpBinding(下面的代碼),將導致我的內容流於沒有實際歸還?

  2. 是否有可能在瀏覽器識別可下載內容類型的方式重定向在jquery中收到的ajax響應,還是這必須使用GET?

服務代碼:

[WebInvoke(Method = "POST", UriTemplate = "UtilizationReport", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json)] 
     public Stream DownloadUtilizationReport(string startDate, string endDate) 
     { 
       DateTime start = DateTime.Parse(startDate); 
       DateTime end = DateTime.Parse(endDate); 
       . 
       .  
       . 

       Stream stream = reportGenerator.GenerateUtilizationReport(exams); 

       WebOperationContext.Current.OutgoingResponse.ContentType = "text/csv"; 
       WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=MediaImport_Utilization_" + startDate + "-" + endDate + ".csv"); 
       return stream; 


     } 

端點配置:從POST

<system.serviceModel> 
    <bindings> 
     <webHttpBinding> 
     <binding name="reportDownload" transferMode="StreamedResponse" /> 
     </webHttpBinding> 
    </bindings> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="webHttpBehavior"> 
      <webHttp faultExceptionEnabled="true" /> 
     </behavior> 
     </endpointBehaviors> 
     <serviceBehaviors> 
     <behavior name=""> 
      <serviceMetadata httpGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="true" /> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <services>   
     <service name="Poiesis.MediaImport.ReportingService"> 
     <endpoint address="rest" binding="webHttpBinding" bindingConfiguration="reportDownload" behaviorConfiguration="webHttpBehavior" 
      name="restEndpoint" contract="Poiesis.MediaImport.IReportingService" /> 
     </service> 
    </services> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
     multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 

收到響應:

HTTP/1.1 200 OK 
Cache-Control: private 
Content-Type: text/csv 
Server: Microsoft-IIS/7.5 
Content-Disposition: attachment; filename=MediaImport_Performance2000-01-01-2012-01-01.csv 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Tue, 18 Oct 2011 15:32:47 GMT 
Content-Length: 0 
+0

任何運氣嗎?我得到同樣試圖做到這一點,我不得不改變,以CreateTextResponse而非CreateStreamResponse –

+0

不,我無法得到它的時候工作,所以我最終只是拋出了一個ASP頁面重定向到,並提供下載的文件。我比我想要的更笨,但解決了問題。 – JMorgan

回答

3

當你通過服務調用步進,請確認流中的位置已設置到0;如果您的GenerateUtilizationReport方法正在寫入流,但未重置要啓動的流的位置,那麼當WCF開始讀取它時,它將不會找到其他任何東西。如果這是一個MemoryStream,只需在返回之前將其Position屬性設置爲0即可。

+1

我已經試過了,但stream.Seek(0,0),我剛試過的位置設置爲0爲好。沒有任何影響。 – JMorgan

+0

嘗試stream.Position = 0; stream.Flush(); –

0

使它成爲一個GET請求,並設置了window.location到服務url.This將「帽子戲法」的瀏覽器,它會開始下載。