如何以编程方式为BasicHttpBinding指定HTTPS?

时间:2013-06-14 04:41:16

标签: .net web-services .net-4.0 https ssl-certificate

我尝试在.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);

2 个答案:

答案 0 :(得分:1)

你应该使用BasicHttpBinding,但是BasicHttp s 绑定。它会解决我猜的问题。

答案 1 :(得分:0)

您可以将HTTPS与 WsHttpBinding 一起使用,而不是与BasicHttpBinding一起使用。确保使用您要使用的配置启动服务器,然后尝试从客户端进行连接。

相关问题