abh*_*hek 0 .net c# windows wcf web-services
我一直在创建一个新的服务来下载大文件到客户端.我想在Windows服务中托管该服务.在服务中我写道:
public class FileTransferService : IFileTransferService
{
private string ConfigPath
{
get
{
return ConfigurationSettings.AppSettings["DownloadPath"];
}
}
private FileStream GetFileStream(string file)
{
string filePath = Path.Combine(this.ConfigPath, file);
FileInfo fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
throw new FileNotFoundException("File not found", file);
return new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
}
public RemoteFileInfo DownloadFile(DownloadRequest request)
{
FileStream stream = this.GetFileStream(request.FileName);
RemoteFileInfo result = new RemoteFileInfo();
result.FileName = request.FileName;
result.Length = stream.Length;
result.FileByteStream = stream;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
界面看起来像:
[ServiceContract]
public interface IFileTransferService
{
[OperationContract]
RemoteFileInfo DownloadFile(DownloadRequest request);
}
[DataContract]
public class DownloadRequest
{
[DataMember]
public string FileName;
}
[DataContract]
public class RemoteFileInfo : IDisposable
{
[DataMember]
public string FileName;
[DataMember]
public long Length;
[DataMember]
public System.IO.Stream FileByteStream;
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我打电话给服务时,它说"基础连接已关闭".您可以获得实施 http://cid-bafa39a62a57009c.office.live.com/self.aspx/.Public/MicaUpdaterService.zip 请帮帮我.
我在您的服务中找到了非常好的代码:
try
{
host.Open();
}
catch {}
Run Code Online (Sandbox Code Playgroud)
这是最糟糕的反模式之一!立即用正确的错误处理和日志记录替换此代码.
我没有测试你的服务,只是通过查看配置和你的代码,我建议它永远不会工作,因为它不符合HTTP流式传输的要求.当您想通过HTTP方法流时,必须只返回Stream类型的单个主体成员.您的方法返回数据合同.使用此版本:
[ServiceContract]
public interface IFileTransferService
{
[OperationContract]
DownloadFileResponse DownloadFile(DownloadFileRequest request);
}
[MessageContract]
public class DownloadFileRequest
{
[MessageBodyMember]
public string FileName;
}
[MessageContract]
public class DownloadFileResponse
{
[MessageHeader]
public string FileName;
[MessageHeader]
public long Length;
[MessageBodyMember]
public System.IO.Stream FileByteStream;
}
Run Code Online (Sandbox Code Playgroud)
不要关闭服务上的流.关闭流是客户的责任.