2014-08-27 53 views
1

我有一个标准的WCF(.svc)服务,通常会说JSON。我需要创建一个方法来返回一个PDF文件。如何从Web Service返回文件?

我能做到这一点(理论上,还没有尝试过)

public Byte[] GetDocument(string DocumentName) 
{ 
    string strdocPath; 
    strdocPath = "C:\\DocumentDirectory\\" + DocumentName; 

    FileStream objfilestream = new FileStream(strdocPath,FileMode.Open,FileAccess.Read); 
    int len = (int)objfilestream.Length;   
    Byte[] documentcontents = new Byte[len]; 
    objfilestream.Read(documentcontents,0,len); 
    objfilestream.Close(); 

    return documentcontents; 
} 

但我需要指定文件名,这我不知道如何在这方面做。

在常规asp.net的MVC,我这样做:

Response.Clear(); 
Response.ClearHeaders(); 
Response.ContentType = file.ContentType; 
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.FileName + "\""); 
Response.AddHeader("Content-Length", file.FileSize.ToString()); 
Response.OutputStream.Write(file.Bytes, 0, file.Bytes.Length); 
Response.Flush(); 
Response.End(); 

但响应对象似乎并不在一个WCF项目周围。

我是否缺少一些简单的东西?

+1

返回'Stream'。我想,你可以使用* OperationContext *或* WebOperationContext *来设置标题。 – 2014-08-27 22:08:26

回答

2

我使用它是这样的:

string agent = WebOperationContext.Current.IncomingRequest.Headers["User-Agent"]; 

if (agent.Contains("MSIE") == false) 
{ 
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream"; 
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "inline; filename=\"{0}\"".Fill(attachment.Filename)); 
} 
else 
{ 
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream"; 
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-Disposition", "attachment; filename=\"{0}\"".Fill(attachment.Filename)); 
    WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Download-Options", "noopen"); 
    WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Content-Type-Options", "nosniff"); 
} 

return new MemoryStream(attachment.Data); 
相关问题