開發 Web API 的 SSL 設定卡到了一些關卡,順便測了幾個情境
本文連結
開發環境
VS 2019
.NET Framework 4.7.2
@Server
Install-Package swagger-net
這個 Lab 目的是為了演練 SSL,我用 Scaffold 產生 API,就夠用了
SSL Enabled
設定兩個動作,SSL Enabled=true, 啟動頁面 = SSL URL
按下 Ctrl+F5 應該就能開啟瀏覽頁並直接訪問 SSL URL
如果有跳出這個畫面,按下 Yes
憑證會裝在 Console Root / Certificates - Current User / Trusted Root Certification Authorities / Certificates
故障排除
按下 Ctrl+F5 連不到 SSL URL
可以嘗試這樣做
修復你的 IIS Express
修復後,重啟 VS IDE → Enable SSL,應該就會出現這個畫面
或是執行以下命令
cd C:\Program Files (x86)\IIS Express
IisExpressAdminCmd.exe setupsslUrl -url:https://localhost:44397/ -UseSelfSigned
無法讀取憑證,Unable to read data from the transport connection
出現 System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. 例外訊息
我在 CI Server 執行自動化測試,噴了這這錯誤
Assembly Initialization method THS.ERP.MM.WebAPI.UnitTest.MsTestHook.Initialize threw exception. System.AggregateException: System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host. Aborting test execution.
設定憑證讀取權限,就可以解決
@Client
需要驗證未信任的憑證
可以選擇用 HttpClientHandler+HttpClient
private static readonly HttpClient s_client; //private static string s_baseUrl = "http://localhost:6672"; private static readonly string s_baseUrl = "https://localhost:44349"; static Form1() { var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = (request, cert2, cetChain, policyErrors) => { //可以在這裡處理憑證 return true; }; if (s_client == null) { s_client = new HttpClient(handler); s_client.BaseAddress = new Uri(s_baseUrl); } }
假如 Client 是 Web 還可以選擇用
ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
信任憑證
除了用程式控制驗證之外,還可以把 Server 的憑證匯出來,匯到 Trusted Root Certification Authorities
匯出憑證
匯入憑證
專案位置
https://github.com/yaochangyu/sample.dotblog/tree/master/WebAPI/Lab.WebApiSsl
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET