2011-07-25 42 views
2

任務:在用戶單擊鏈接(這是WCF服務{例如:http://localhost:6186/MyReportServices.svc/reports/012})時能夠呈現PDF。該服務將從SSRS服務器獲取報告並返回流。這是一段代碼。使用WCF Restful Services的PDF

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)] 
public class AssistReportServices : IAssistReportServices 
{ 
    public Stream GetReport(int value) 
    { 
     //skipped some lines of code. 
     try 
     { 
      result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); 
      execInfo = rs.GetExecutionInfo();    
     } 
     catch (SoapException err) 
     { 
      throw; 
     } 
     MemoryStream ms = new MemoryStream(); 
     ms.Write(result, 0, result.Length); 
     ms.Position = 0; 
     //WebOperationContext.Current.OutgoingResponse.ContentType = ConfigurationManager.AppSettings["ResponseType"]; 
     WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf"; 
     return ms; 
    } 
} 

我的工作合同是這樣的:

[OperationContract(Action = "*")] 
[WebInvoke(Method = "POST", 
    UriTemplate = "reports/{value}")] 
Stream GetReport(int value); 

到目前爲止好。但是,這是問題...當我點擊上面的鏈接時,在標題爲Adobe Reader和消息的對話框中出現以下錯誤:

文件不以'%PDF-'開頭。

錯誤圖片:http://i.imgur.com/A4J68.png

我可以將內存流保存到一個文件並手動打開PDF,它會打開就好了沒有問題。

謝謝。

+0

錯誤消息看起來更像是一個問題Acrobat認爲它打開了一個名爲'012'的文件,而不是一個名爲'012.pdf'的文件等。 –

回答

2

我發現我錯了。我曾使用Web.Config文件來配置我的WCF服務。當我使用下面的代碼切換到基於代碼的配置時,服務工作並指出了我的錯誤。

static void Main(string[] args) 
{ 

    ServiceHost serviceHost = new ServiceHost(typeof(MyReportingServices.MyReportServices), ServiceEndpointUri); 
    WebHttpBinding binding = new WebHttpBinding(); 
    ServiceEndpoint sep = serviceHost.AddServiceEndpoint(typeof(MyReportingServices.IMyReportServices), binding, string.Empty); 
    sep.Behaviors.Add(new WebHttpBehavior()); 
    serviceHost.Open(); 
    Console.WriteLine("Service is running @ " + ServiceEndpointUri); 
    Console.WriteLine(); 
    Console.WriteLine("Press enter to shutdown service."); 
    Console.ReadLine(); 
    serviceHost.Close(); 
} 

錯誤是:

經營合同「IMyReportServices」 GetReport「有一個名爲「價值」不具有類型「串」的路徑 變量。 UriTemplate路徑段的變量 必須具有類型「字符串」。

我通過將我的操作參數的數據類型更改爲String來解決這個問題。

由於Mrchief,我用自己的輸入添加以下代碼行,幫我顯示保存/取消對話框: -

WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf"; 
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-disposition", "inline; filename=apurvReport.pdf"); 
+0

不要忘記標記爲答案 - 回答自己的問題是有效的。 –

+0

謝謝。不允許我在24小時之前標記答案。可能是由於我的用戶級別。 – Apurv

0

你如何將它發送到瀏覽器?它看起來像被髮送了一個錯誤的啞劇類型。它應該作爲Response.ContentType = "application/pdf";

+0

更新了問題,web.config文件具有鍵值對: Apurv

+0

是的,但你在哪裏寫它的響應流? – Mrchief

+0

該服務是REST-ful,所以我應該能夠在我的HTML頁面中嵌入鏈接http:// localhost:6186/MyReportServices.svc/reports/012作爲定位標記。我的服務應該將響應傳回給瀏覽器,並且瀏覽器應該提示一個打開保存對話框。如果我的理解不正確,請原諒我。 – Apurv