我有一个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