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

WCF 分散式開發常見錯誤 (26):驗證失敗,遠端關閉傳輸流

     編輯:關於.NET

錯誤現象

Authentication failed because the remote party has closed the transport stream.

在添加服務引用(HTTPS + mex)時發生,導致無法獲取元數據。

根因分析

核心原因:憑證配置不正確,具體表現為:

  • 伺服器憑證未正確向 HTTP.SYS 註冊(HTTPS 情況)。
  • 客戶端與服務端安全綁定不匹配。
  • 客戶端提供的憑證未被服務端信任(未安裝至 Trusted People / Trusted Root CA)。

完整解決步驟

1. 製作可交換金鑰的憑證

使用 makecert(需 Visual Studio 命令提示字元):

rem 伺服器憑證
makecert -sr localmachine -ss My -n "CN=WCFServerPK" -sky exchange -pe -r

rem 客戶端憑證
makecert -sr localmachine -ss My -n "CN=WCFClientPK" -sky exchange -pe -r

-sky exchange 關鍵:標記私鑰可用於金鑰交換(加密/解密),否則會報「must have a private key capable of key exchange」。

2. 匯出含私鑰的 PFX

執行 mmc → 加入「憑證」嵌入式管理單元(電腦帳戶)→ 個人 → 所有任務 → 匯出 → 勾選「匯出私鑰」 → 設定密碼 → 儲存為 .pfx。

3. 安裝至信任存儲區

  • 將 PFX 匯入「受信任的人」存儲區。
  • 將 PFX 匯入「受信任的根憑證授權單位」存儲區。

4. 向 HTTP.SYS 註冊 SSL 憑證(綁定 IP:Port)

Windows Server 2003 / XP (HttpCfg.exe):

httpcfg set ssl -i 0.0.0.0:9001 -h 9174185b2860b6d5ec3de133d5fcc4e1419b09e5

Vista / Server 2008+ (netsh):

netsh http add sslcert ipport=0.0.0.0:9001 certhash=9174185b2860b6d5ec3de133d5fcc4e1419b09e5 appid={11111111-2222-3333-4444-qqqqqqqqqqqq}

certhash 為憑證指紋(Thumbprint),可用 httpcfg query ssl 或 netsh http show sslcert 查看。

5. 服務端配置範例

<service behaviorConfiguration="WCFService.WCFServiceBehavior" name="WCFService.WCFService">
  <endpoint address="WCFService" binding="wsHttpBinding" bindingConfiguration="BindingConfiguration" contract="WCFService.IWCFService"/>
  <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
  <host>
    <baseAddresses><add baseAddress="https://computer:9001/"/></baseAddresses>
  </host>
</service>

<wsHttpBinding>
  <binding name="BindingConfiguration">
    <security mode="Transport">
      <transport clientCredentialType="Certificate"/>
    </security>
  </binding>
</wsHttpBinding>

<serviceBehaviors>
  <behavior name="WCFService.WCFServiceBehavior">
    <serviceMetadata httpsGetEnabled="true"/>
    <serviceCredentials>
      <serviceCertificate storeName="My" x509FindType="FindBySubjectName" findValue="WCFServerPK" storeLocation="LocalMachine"/>
    </serviceCredentials>
  </behavior>
</serviceBehaviors>

關鍵提醒

  • 開發測試階段皆為自簽憑證,務必雙向匯入信任存儲區。
  • HTTPS 元數據端點需 mexHttpsBinding 且 httpsGetEnabled="true"。
  • 生產環境請使用 CA 簽發憑證,避免手動信任維護成本。

參考資源

MSDN 論壇完整討論串

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