自托管WCF服务使用HTTP而不是HTTPS

本文关键字:HTTP HTTPS WCF 服务 | 更新日期: 2023-09-27 18:26:25

好的,所以我在控制台应用程序中托管WCF服务。

所有绑定都是用程序创建的,因此没有配置设置。

只要我使用HttpTransportBindingElement,我就有一个可用的服务,但只要我使用了HttpsTransportBindingElement,就什么都不起作用,该服务不会在浏览器中显示,客户端应用程序返回405 (Method Not Allowed) CommunicationException

我已经尝试将SecurityBindingElement设置为CustomBinding,但我不确定应该使用哪个选项。

SecurityBindingElement.CreateCertificateOverTransportBindingElement()

SecurityBindingElement.CreateAnonymousForCertificateBindingElement()

等等。

创建主机的代码位于下方

baseAddress = new Uri(string.Format("{0}://{1}", strConnectionType, ConfigurationManager.AppSettings["baseAddress"]));
            ServiceHost host = new ServiceHost(typeof(IMyService), baseAddress);
            host.AddServiceEndpoint(typeof(MyService), binding, String.Empty);
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpsGetEnabled = certificate != null;
            smb.HttpGetEnabled = certificate == null;
            host.Description.Behaviors.Add(smb);
            ServiceDebugBehavior sdb = host.Description.Behaviors.Find<ServiceDebugBehavior>();
            if (sdb == null)
            {
                host.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
            }
            else
            {
                if (!sdb.IncludeExceptionDetailInFaults)
                {
                    sdb.IncludeExceptionDetailInFaults = true;
                }
            }

            if (certificate != null)
            {
                host.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, certificate.Thumbprint);
            }

自托管WCF服务使用HTTP而不是HTTPS

我关注了这个博客http://blogs.msdn.com/b/james_osbornes_blog/archive/2010/12/10/selfhosting-a-wcf-service-over-https.aspx其中强调,为了使HTTPS发挥作用,您需要将端口绑定到您正在使用的证书。

Process bindPortToCertificate = new Process();bindPortToCertificate.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "netsh.exe");

bindPortToCertificate.StartInfo.Arguments = string.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", port, certificate.Thumbprint, Guid.NewGuid());

bindPortToCertificate.Start();

bindPortToCertificate.WaitForExit();

一旦完成,一切都奏效了。

如果有人需要我的示例代码来设置和配置带有程序设置绑定的自托管WCF服务器,请与我联系。:)