我有一個ASP.NET Web API,我希望使用ssl。目前服務器正在使用自簽名證書,並且此時都允許http和https。我有一個非常基本的測試客戶端,可以正常使用http,但不適用於https。我想知道如何修改下面的客戶端代碼,以便它可以使用https。目前,IE,Firefox和Chrome都可以使用http和https(帶有證書警告)連接到Web API,所以這使我相信我不應該修改服務器上的任何內容,只需在客戶端代碼中修改。這裏的客戶端代碼:.NET客戶端連接到ssl Web API
static void Main(string[] args)
{
try
{
if (args.Length != 1)
{
Console.WriteLine("Please provide a url, and only a url.");
return;
}
var url = new Uri(args[0]);
var urlAuthority = url.GetLeftPart(UriPartial.Authority);
var urlPathQuery = args[0].Substring(urlAuthority.Length);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(urlAuthority);
HttpResponseMessage response = client.GetAsync(urlPathQuery).Result;
if (response.IsSuccessStatusCode)
Console.WriteLine(response.Content.ReadAsAsync<string>().Result); // expecting scalar results only
else
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
catch (Exception ex)
{
Exception tempEx = ex;
while (tempEx != null)
{
Console.WriteLine(tempEx.Message);
tempEx = tempEx.InnerException;
}
}
}
當我運行上面的代碼與我的http url,它工作正常。當我更改URL爲https以下錯誤打印:
One or more errors occurred.
An error occurred while sending the request.
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
The remote certificate is invalid according to the validation procedure.
我有一個問題是,如果客戶端必須手動發送公鑰給服務器,因此它知道如何發送回一個加密的響應,或者如果這在幕後自動發生?第二,現在在看到最後一個錯誤之後,我想知道如果我還需要在客戶端執行其他操作來忽略證書警告,並且相信這個證書可以繼續使用呢?
您是否已將安全模式設置爲在您的配置中傳輸? – Joe 2013-03-04 16:10:04
另一個例子可以在這裏找到:http://stackoverflow.com/a/42449178/112397 – TombMedia 2017-02-24 22:15:30