TTT*_*TTT 22 c# asp.net-web-api
我有一个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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我用我的http 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.
Run Code Online (Sandbox Code Playgroud)
我遇到的一个问题是,客户端是否必须手动将公钥发送到服务器,以便它知道如何发回加密响应,或者这是否在幕后自动发生?第二,现在看到最后一个错误后,我想知道我是否还必须在客户端内做一些其他事情来忽略证书警告并且只相信这个证书可以继续进行?
Opp*_*nal 44
看一下C#忽略证书错误 SO问题.我相信您可以使用ServicePointManager添加证书验证处理程序以绕过证书验证.但是,在生产环境中使用签名证书可能是个好主意.
ServicePointManager
.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;
Run Code Online (Sandbox Code Playgroud)
Ric*_*hur 23
这对我有用.只需在调用GetAsync之前添加以下内容.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Run Code Online (Sandbox Code Playgroud)
这将忽略SSL错误.仅建议在Intranet环境或其他无法伪造服务器标识的封闭网络中使用.
此错误消息表示客户端在SSL握手期间不信任服务器证书。某些浏览器会稍微宽容一些,并为您提供“红色条”,但从代码进行调用将导致401和被拒绝的调用。
您不需要对IIS中的客户端证书设置做任何事情(因为我假设您没有使用客户端证书)。
此异常消息告诉您在客户端上进行验证时,自签名证书链被拒绝。您可能会通过导出(不使用私钥),自签名证书并将其作为根证书安装在客户端计算机上来解决此问题。
如果这不起作用,则需要制作一个新的CA(证书颁发机构证书),然后生成一个用CA签名的新服务器证书。最后,必须将CA作为根证书安装在客户端计算机上。
这是一篇很好的文章,显示了使用makecert和pvk2pfx的过程。
编辑:
看起来可能有一种方法可以配置HttpClient为忽略SSL错误。但是,我强烈建议您从一开始就尽量不要出现SSL错误。
| 归档时间: |
|
| 查看次数: |
51261 次 |
| 最近记录: |