
圖片來源:https://pixabay.com/en/despair-alone-being-alone-archetype-513528/ 有時候需要在C#的程式裡面發出request和內部或者外部的服務溝通,如果內部或者外部的服務只允許https連線,而且的ssl憑證並沒有經過認證(有可能是用self signed certifcate),那麼C#會直接出錯:

錯誤訊息範例畫面 system.security.authentication.authenticationexception the remote certificate is invalid according to the validation procedure
System.Net.Http.HttpRequestException: 傳送要求時發生錯誤。 ---> System.Net.WebException: 基礎連接已關閉: 無法為 SSL/TLS 安全通道建立信任關係。
---> System.Security.Authentication.AuthenticationException: 根據驗證程序,遠端憑證是無效的。
一般來說要解決這個問題有兩個做法:
- 把self sign的certificate裝到程式的機器上面並且信任那個憑證
- 在送出request的時候做一些特殊處理
這篇將會對於第二個做法,調整程式讓發出request遇到這種問題的時候能夠處理這種問題。