我正在尝试在 .NET 4 (Visual Studio 2010) 中使用需要 HTTPS 并通过客户端证书进行身份验证的 Web 服务。目前,我正在编写一个控制台程序,只是为了证明这个概念,但我无法让程序识别它应该使用 https。至少这是错误所暗示的:
向 https:// 发出 HTTP 请求时出错。这可能是由于在 HTTPS 情况下未使用 HTTP.SYS 正确配置服务器证书。这也可能是由于客户端和服务器之间的安全绑定不匹配造成的。
这是我正在使用的示例代码:
class Program
{
static void Main(string[] args)
{
try
{
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
Uri baseAddress = new Uri("https://<host>:<port>/<endpoint>");
var certificate = new X509Certificate2("<localpath to certificate>.p12", "<password>");
EndpointAddress endpointAddress = new EndpointAddress(baseAddress);
ChannelFactory<LinePortType> factory = new ChannelFactory<LinePortType>(binding, endpointAddress);
factory.Credentials.ClientCertificate.Certificate = certificate;
LinePortType proxy = factory.CreateChannel();
var header = new ctSoapHeaderMsg();
var response = new object();
var request = new PerformServiceRequest(header, "<string>");
var responseCode = proxy.PerformService(request);
Console.WriteLine("Response Code :" + responseCode.ToString());
Console.WriteLine("Response :" + response.ToString());
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
Console.ReadLine(); // Pause
}
}
我已经用占位符替换了一些敏感字符串。
问题完全可能是我无法正确配置证书。最终,我希望从本地证书存储中加载它,这样我就不必在代码或配置中指定密码。
LinePortType 是基于本地 WSDL 的服务引用。因为 WSDL 用于生产环境,所以我将端点更改为引用 UAT 环境。
根据 srsyogesh 的建议,我已经更新为使用 WSHttpBinding,但我仍然遇到同样的错误。
try 中的代码现在看起来像:
var binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var baseAddress = new Uri("https://<host>:<port>/<endpoint>");
var endpointAddress = new EndpointAddress(baseAddress);
var client = new LinePortTypeClient(binding, endpointAddress);
client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByIssuerName, "<issuername>");
var header = new ctSoapHeaderMsg();
var response = new object();
var responseCode = client.PerformTelstraSQ(ref header, "<string>", out response);
Console.WriteLine("Response Code :" + responseCode);
Console.WriteLine("Response :" + response);