好的,我在控制台应用程序中托管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);
}
Run Code Online (Sandbox Code Playgroud)
我关注了这个博客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服务器与编程设置绑定.:)