我无法将 wav 文件(从 Silverlight 4)上传到服务器(WCF .NET 4)。该文件从 SL 上传到服务器并将其写入磁盘。但是上传的文件被改变了。这两个文件(上传前和上传后的文件)大小完全相同,但内容不同。我尝试在普通控制台程序中上传,它工作正常。似乎 WCF 在序列化来自 SL 的数据时做了一些事情。任何人都知道发生了什么事吗?
服务代码如下:
[ServiceContract(Namespace = "")]
interface ISoundService
{
[OperationContract]
int UploadSound(UploadSoundFile file);
}
public int UploadSound(UploadSoundFile file)
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/" + file.FileName;
File.WriteAllBytes(path, file.File);
return 0;
}
[DataContract]
public class UploadSoundFile
{
[DataMember]
public string FileName;
[DataMember]
public byte[] File;
}
服务配置是
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service.SoundService.customBinding0" maxReceivedMessageSize="2000000" maxBufferSize="2000000">
<readerQuotas maxArrayLength="2000000" maxStringContentLength="2000000"/>
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="Service.SoundServiceBehavior" name="Service.SoundService">
<endpoint address="" binding="basicHttpBinding" contract="Service.ISoundService" bindingConfiguration="Service.SoundService.customBinding0"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service.SoundServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Silverlight 客户端是:
private static int uploadSoundOnServer(string fileName, Stream stream)
{
SoundServiceClient c = new SoundServiceClient();
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, checked((int)stream.Length));
UploadSoundFile file = new UploadSoundFile() { FileName= fileName, File = buffer, };
c.UploadSoundAsync(file);
return 0;
}
我发现了问题。它与 WCF 或 SL 无关。问题是关于 IO,stream。
在 SL 应用程序中,流位置不是 0,因为它之前被操纵过。因此,在调用 stream.Read(...) 之前将位置更改回 0 时它会起作用。但我仍然想知道为什么它仍然能够读取整个流,即使位置之前不是 0(即使我将长度设置为(int)stream.Length)。也许当它到达流的末尾时,它会返回并再次从头开始读取?
我是一名优秀的程序员,十分优秀!