using (var handler = new WebRequestHandler())
{
handler.ServerCertificateValidationCallback = ...
using (var client = new HttpClient(handler))
{
...
}
}
108
或者您可以使用 Windows.Web.Http 命名空间中的 HttpClient :
var filter = new HttpBaseProtocolFilter();
#if DEBUG
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
...
}
2
如果你是一个简单的解决方案,只需在你的处理程序中返回 true 的所有风险 . 我把安全留给你 .
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
var client = new HttpClient(handler);
using System.Security.Cryptography.X509Certificates;
using System.Net;
public class MyPolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request,
int certificateProblem)
{
//Return True to force the certificate to be accepted.
return true;
}
}
然后在发送您的http请求之前使用它,如下所示:
System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();
8 回答
使用Windows 8.1,您现在可以信任无效的SSL证书 . 您必须使用Windows.Web.HttpClient,或者如果您想使用System.Net.Http.HttpClient,您可以使用我写的消息处理程序适配器:http://www.nuget.org/packages/WinRtHttpClientHandler
文档在GitHub上:https://github.com/onovotny/WinRtHttpClientHandler
一个快速而肮脏的解决方案是使用ServicePointManager.ServerCertificateValidationCallback委托 . 这允许您提供自己的证书验证 . 验证在整个App域中全局应用 .
我主要用于单元测试,我希望针对我正在进行托管的 endpoints 运行并尝试用WCF client或HttpClient命中它 .
对于 生产环境 代码,您可能需要更细粒度的控制,并且最好使用WebRequestHandler及其ServerCertificateValidationCallback委托属性(请参阅dtb's answer below) . 或使用HttpClientHandler ctacke answer . 我现在更喜欢这两个中的任何一个,即使我使用我的过去的集成测试,除非我找不到任何其他钩子 .
看看WebRequestHandler Class及其ServerCertificateValidationCallback Property:
或者您可以使用
Windows.Web.Http
命名空间中的 HttpClient :如果你是一个简单的解决方案,只需在你的处理程序中返回
true
的所有风险 . 我把安全留给你 .如果这是针对Windows运行时应用程序,则必须将自签名证书添加到项目中并在appxmanifest中引用它 .
文档在这里:http://msdn.microsoft.com/en-us/library/windows/apps/hh465031.aspx
如果来自不受信任的CA(如机器本身不信任的私有CA),则需要获取CA的公共证书,将其作为内容添加到应用程序,然后将其添加到清单中 .
完成后,应用程序会将其视为正确签名的证书 .
我没有答案,但我确实有另一种选择 .
如果您使用Fiddler2来监控流量并启用HTTPS解密,则您的开发环境不会抱怨 . 这不适用于WinRT设备,例如Microsoft Surface,因为您无法在其上安装标准应用程序 . 但是你的开发Win8电脑会很好 .
要在Fiddler2中启用HTTPS加密,请转至 Tools > Fiddler Options > HTTPS (Tab) > Check "Decrypt HTTPS Traffic" .
我将继续关注这个线索,希望有人能有一个优雅的解决方案 .
我在网上找到了一个似乎运作良好的例子:
首先你创建一个新的ICertificatePolicy
然后在发送您的http请求之前使用它,如下所示:
http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/