我必须创建一个允许下载pdf的WCF服务(.net 4.5),而不是REST模式。
我以这种方式定义界面
[ServiceContract]
public interface IService1
{
[OperationContract]
Stream GetPdfFile();
}
以这种方式实现GetPdfFile
public Stream GetPdfFile()
{
Stream ret = null;
try
{
string downloadFilePath = @"C:\Users\jjkdk\Desktop\WTI_PETERS.pdf";
string fileName = downloadFilePath.Substring(downloadFilePath.LastIndexOf(@"\") + 1);
String headerInfo = "attachment; filename=" + fileName;
WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
ret = File.OpenRead(downloadFilePath);
}
catch (Exception ex)
{
throw ex;
}
return ret;
}
app.config中的服务标签如下:
<system.serviceModel>
<services>
<service name="WCFAperturaAllegatiCrm.Service1">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8733/Design_Time_Addresses/WCFAperturaAllegatiCrm/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="WCFAperturaAllegatiCrm.IService1">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
然后我创建了一个控制台客户端,上面运行WCF,在url服务中添加了一个服务引用,并在控制台中插入了以下代码:
SrvAperturaAllegati.Service1Client srv = new SrvAperturaAllegati.Service1Client();
Stream stream = srv.GetPdfFile();
Console.WriteLine();
我收到以下例外:
System.ServiceModel.ProtocolException:内容类型text / html; charset = utf-&gt; 8响应消息与绑定的内容类型&gt;(application / soap + xml; charset = utf-8)不匹配。如果使用自定义编码器,请确保&gt;正确实现了IsContentTypeSupported方法。响应的前1024个字节&gt;是:........
我在没有结果的情况下挣扎。
有人可以帮助我吗?
答案 0 :(得分:0)
此问题来自
....
WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
...
如果您想将此服务用作SOAP服务,则无法添加OutgoingResponse.Headers和OutgoingResponse.ContentType。评论这一行,它将在SOAP中正常工作。这行是用于REST服务的。
此处更正的代码:
public Stream GetPdfFile()
{
Stream ret = null;
try
{
string downloadFilePath = @"C:\Users\jjkdk\Desktop\WTI_PETERS.pdf";
string fileName = downloadFilePath.Substring(downloadFilePath.LastIndexOf(@"\") + 1);
String headerInfo = "attachment; filename=" + fileName;
//WebOperationContext.Current.OutgoingResponse.Headers["Content-Disposition"] = headerInfo;
//WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
ret = File.OpenRead(downloadFilePath);
}
catch (Exception ex)
{
throw ex;
}
return ret;
}