我有一个WCF webService方法,该方法将返回文件:
在IMainService中:
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/PerformScan")]
Stream PerformScan();
在MainService.cs中:
public Stream PerformScan()
{
MemoryStream SomeStream = new MemoryStream();
// Filling this memory stream using some processes on the data
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-disposition", "inline; filename=Scan.Tiff");
return SomeStream;
}
这是我的App.Config:
<system.serviceModel>
<services>
<service name="ShamsScanner.WCF.ScanService" behaviorConfiguration="mexBehavior">
<endpoint address="" binding="webHttpBinding" contract="ShamsScanner.WCF.IScanService" behaviorConfiguration="web"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:1369"/>
<add baseAddress="net.tcp://localhost:1369"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="mexBehavior">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
当我在浏览器中调用此函数时。它不会返回任何内容。通过使用下载管理器,我将看到此方法将不断触发,并且……什么都没有。
我已经将此MemoryStream写在文件上,并且看到它不为空。
我应该怎么做才能返回文件?
答案 0 :(得分:0)
感谢楼主的提示,我们需要重新定位内存流的位置。
Stream ms = new MemoryStream();
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
fs.CopyTo(ms);
ms.Position = 0;
我已经制作了一个有关如何使用Filestream下载文件的演示。
IService。
[OperationContract]
[WebGet]
Stream Download();
Service.cs
public Stream Download()
{
string file = @"C:\1.png";
try
{
//MemoryStream ms = new MemoryStream();
//Stream stream = File.OpenRead(file);
FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
//byte[] bytes = new byte[fs.Length];
//fs.Read(bytes, 0, (int)fs.Length);
//ms.Write(bytes, 0, (int)fs.Length);
WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Content-disposition", "inline; filename=Scan.Tiff");
return fs;
//return Stream;
}
catch (Exception ex)
{
return null;
}
}
配置。
<service name="WcfServiceFile.Service1">
<endpoint address="" binding="webHttpBinding" contract="WcfServiceFile.IService1" behaviorConfiguration="beh">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="beh">
<webHttp />
</behavior>
</endpointBehaviors>