我正在尝试使用 .NET 4 (Visual Studio 2010) 中的 Web 服务,该服务需要 HTTPS 并使用客户端证书进行身份验证。目前,我正在编写一个控制台程序,只是为了证明这个概念,但我无法让程序识别它应该使用 https。至少错误表明的是这样的:
An error occurred while making the HTTP request to https://. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be cause by a mismatch of the security binding between the client and the server.
这是我正在使用的示例代码:
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);
最佳答案
您不应该使用 BasicHttpBinding,而应该使用 BasicHttpsBinding。我想它会解决这个问题。
关于.net - 如何以编程方式为 BasicHttpBinding 指定 HTTPS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17101217/