C# 在WCF REST服务中返回非JSON、非XML数据
我建立了一个WCF Rest服务项目,为JSON数据结构提供服务。我在接口文件中定义了一个合同,如:C# 在WCF REST服务中返回非JSON、非XML数据,c#,.net,wcf,C#,.net,Wcf,我建立了一个WCF Rest服务项目,为JSON数据结构提供服务。我在接口文件中定义了一个合同,如: [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "location/{id}")] Location GetLocation(string id
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "location/{id}")]
Location GetLocation(string id);
现在,Web服务需要像标准Web服务器一样返回多媒体(图像、PDF文档)文档。ResponseFormat
的WCFWebMessageFormat
仅支持JSON或XML。如何在接口中定义返回文件的方法
比如:
[OperationContract]
[WebInvoke(Method="GET",
ResponseFormat = ?????
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "multimedia/{id}")]
???? GetMultimedia(string id);
所以:
wgethttp://example.com/multimedia/10
返回id为10的PDF文档。您可以从RESTful服务获取文件,如下所示:
[WebGet(UriTemplate = "file")]
public Stream GetFile()
{
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt";
FileStream f = new FileStream("C:\\Test.txt", FileMode.Open);
int length = (int)f.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
byte[] buffer = new byte[length];
int sum = 0;
int count;
while((count = f.Read(buffer, sum , length - sum)) > 0 )
{
sum += count;
}
f.Close();
return new MemoryStream(buffer);
}
当您在IE中浏览到该服务时,它应该显示一个打开的响应保存对话框
注意:您应该为服务返回的文件设置适当的内容类型。在上面的示例中,它返回一个文本文件。看看这个:Thank you pdiddy它解决了这个问题并包含了一些有趣的附加信息。谢谢。注:文本文件的内容类型通常为“文本/普通”。