我有一个 ASP.NET Web API,我想将其与 ssl 一起使用。当前服务器使用的是自签名证书,此时允许使用 http 和 https。我有一个非常基本的测试客户端,它适用于 http,但不适用于 https。我想知道如何修改下面的客户端代码,以便它可以使用 https。目前,IE、Firefox 和 Chrome 都可以使用 http 和 https(带有证书警告)连接到 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.
我的一个问题是客户端是否必须手动向服务器发送一个公钥以便它知道如何发回加密的响应,或者这是否会在幕后自动发生?其次,在看到最后一个错误之后,我想知道我是否还必须在客户端中执行其他操作以忽略证书警告并只相信该证书可以继续处理?
最佳答案
看看 C# Ignore certificate errors所以问题。我相信您可以使用 ServicePointManager 添加证书验证处理程序来规避证书验证。不过,在您的生产环境中使用签名证书可能是个好主意。
ServicePointManager
.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
关于c# - .NET 客户端连接到 ssl Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15205814/