首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

WCF 串流傳輸機制:大型檔案上傳下載的最佳化實作

     編輯:關於.NET

WCF Streaming (串流) 允許接收端在訊息尚未完整接收時即開始處理,大幅降低大型訊息 (圖片、影片、報表) 的記憶體佔用與延遲。預設 Buffered 模式需完整緩衝後再處理,易造成 OOM 或長時間阻塞。

支援串流的綁定與設定

  • BasicHttpBinding、NetTcpBinding、NetNamedPipeBinding 支援。
  • 設定 transferMode:Streamed (雙向)、StreamedRequest、StreamedResponse。
  • HTTP 協定預設最大訊息 64KB,需調大 maxReceivedMessageSize。
<basicHttpBinding>
  <binding name="streamedBinding" transferMode="Streamed" 
           maxReceivedMessageSize="20000000" />
</basicHttpBinding>

服務契約設計規則

串流操作的參數或回傳值 只能有一個 且型別為 Stream 或其衍生類 (MemoryStream、FileStream 不可序列化,勿直接用作參數)。

[ServiceContract]
public interface IFileService
{
    [OperationContract]
    Stream DownloadFile(string fileName);        // 回傳串流

    [OperationContract]
    void UploadFile(Stream fileStream);          // 參數串流

    [OperationContract(IsOneWay = true)]
    void UploadFileOneWay(Stream fileStream);    // 單向上傳
}

服務端實作範例

public Stream DownloadFile(string fileName)
{
    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
    var bytes = File.ReadAllBytes(path); // 示範用;大檔案建議 File.OpenRead 直接回傳 FileStream
    return new MemoryStream(bytes);
}

public void UploadFile(Stream stream)
{
    using (var fs = File.Create("uploaded.dat"))
    {
        stream.CopyTo(fs); // .NET 4+ 直接複製串流
    }
}

常見坑與解決

  • NetTcpBinding 串流逾時:錯誤 「The socket connection was aborted... receive timeout exceeded」。原因在於串流傳輸期間無應用層心跳,超過 receiveTimeout (預設 10 分鐘) 被斷開。解法:調大 receiveTimeout 或改用 Buffered 模式傳輸小檔案。
  • FileStream 無法序列化:跨機器呼叫必須用 MemoryStream 或自訂 Stream 實作 IXmlSerializable。
  • 串流與可靠會話衝突:reliableSession enabled="true" 不相容於 transferMode="Streamed"。

現代替代方案

.NET Core / ASP.NET Core 原生支援 IAsyncEnumerable<byte[]>、FileStreamResult、gRPC 串流,效能與跨平台優於 WCF Streaming,建議新專案採用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved