本節建立完整的 WCF 自宿主範例,零配置下驗證 NetTcpBinding 的預設安全行為:傳輸安全模式 + Windows 憑證 + 加密簽名。
[ServiceContract]
public interface IHelloService {
[OperationContract]
string GetHello();
}
public class HelloService : IHelloService {
public string GetHello() {
if (ServiceSecurityContext.Current != null &&
!ServiceSecurityContext.Current.IsAnonymous) {
return "Hello: " + ServiceSecurityContext.Current.PrimaryIdentity.Name
+ "; type=" + ServiceSecurityContext.Current.PrimaryIdentity.AuthenticationType;
}
return "hello";
}
}
宿主為主控台程式,配置檔中 <netTcpBinding> 僅指定名稱,無任何 <security> 子元素:
<netTcpBinding>
<binding name="tcpWindowsSecurity">
<!-- 無 security 區塊,完全依賴預設值 -->
</binding>
</netTcpBinding>
在客戶端加入 <clientVia> 導向 TcpTrace 監聽埠 (64590),執行後抓包顯示:無法看到明文內容,證明已加密。

圖 1 預設 Transport 安全模式下的加密流量
| 形式 | 等價內容 |
|---|---|
| 程式碼建構 | new NetTcpBinding() { Security = { Mode = SecurityMode.Transport, Transport = { ClientCredentialType = TcpClientCredentialType.Windows, ProtectionLevel = ProtectionLevel.EncryptAndSign } } } |
| 配置檔完整展開 | <security mode="Transport"><transport protectionLevel="EncryptAndSign" clientCredentialType="Windows"/></security> |
核心結論:NetTcpBinding 預設即啟用傳輸層安全、Windows 整合驗證、訊息加密與簽名,無需額外配置即具備企業級安全基線。
作者:玄魂
出處:https://www.cnblogs.com/xuanhun/