【发布时间】:2012-11-16 18:09:16
【问题描述】:
我对 WCF 服务还很陌生,希望能得到一些帮助。我正在尝试将 WCF 作为服务运行,并让另一台机器上的 ASP.net 客户端能够通过连接到 WCF 服务将文件上传到它。
我正在使用简单的上传设置(来自here)对其进行测试,如果我只是将 WCF 服务引用为“dll”,它可以正常工作,但如果我尝试将它作为 WCF 服务运行,它会给我一个“UploadFile”方法的错误,指出它不受支持。
方法名称上带有红色 X 的确切消息:WCF 测试客户端不支持此操作,因为它使用 FileUploadMessage 类型。
我首先在 Visual Studio 2012 中创建一个 WCF 服务应用程序,并在我的界面 (IUploadService.cs) 中有以下内容:
[ServiceContract]
public interface IUploadService
{
[OperationContract(IsOneWay = true)]
void UploadFile(FileUploadMessage request);
}
[MessageContract]
public class FileUploadMessage
{
[MessageBodyMember(Order = 1)]
public Stream FileByteStream;
}
它是这样实现的(UploadService.svc.cs):
public void UploadFile(FileUploadMessage request)
{
Stream fileStream = null;
Stream outputStream = null;
try
{
fileStream = request.FileByteStream;
string rootPath = ConfigurationManager.AppSettings["RootPath"].ToString();
DirectoryInfo dirInfo = new DirectoryInfo(rootPath);
if (!dirInfo.Exists)
{
dirInfo.Create();
}
// Create the file in the filesystem - change the extension if you wish,
// or use a passed in value from metadata ideally
string newFileName = Path.Combine(rootPath, Guid.NewGuid() + ".jpg");
outputStream = new FileInfo(newFileName).OpenWrite();
const int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead = fileStream.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.Write(buffer, 0, bufferSize);
bytesRead = fileStream.Read(buffer, 0, bufferSize);
}
}
catch (IOException ex)
{
throw new FaultException<IOException>(ex, new FaultReason(ex.Message));
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
}
} // end UploadFile
从外观上看应该可以,但是从我通过查看几个 stackoverflow 和其他论坛问题的理解来看,即使我们可以绑定类型流,WCF 似乎也不支持 Stream。我对此以及我做错了什么感到困惑。
感谢您的帮助。
【问题讨论】:
标签: c# asp.net wcf wcf-binding filestream