So the Microsoft.Web.Administration API is very easy to use to create HTTP and HTTPS bindings for sites:
using (ServerManager manager = new ServerManager())
{
Site site = manager.Sites[siteName];
site.Bindings.Clear();
site.Bindings.Add("*:80:", "http");
site.Bindings.Add("*:443:", "https");
manager.CommitChanges();
}
But the HTTPS binding is pretty meaningless without the SSL certificate. How can I go about programatically choosing a cert file and using it with the HTTPS binding, using this API?
Under Install and Manage SSL for your site (HTTPS), click Manage SSL Sites. Scroll down to the Install an SSL Website and click Browse Certificates. Select the certificate that you want to activate and click Use Certificate. This will auto-fill the fields for the certificate.
Create an SSL Binding Click Add... to add your new SSL binding to the site. The default settings for a new binding are set to HTTP on port 80. Select https in the Type drop-down list. Select the self-signed certificate you created in the previous section from the SSL Certificate drop-down list and then click OK.
I feel like it's important to highlight Devator's comment in this answer. There appears to be a bug that prevents the certificate changes from taking place and I would never have solved it without seeing this comment.
If you set the binding information to itself, this causes IIS to bind the certificate. A quick example is shown below:
binding.BindingInformation = binding.BindingInformation;
The namespace doesn't contain an API for this, so you have to use its ConfigurationMethod
to invoke an extension to the Win API that performs this function. Something like:
string certificateHash = <hash>
string certificateStore = <storename> #my, localmachine, etc
ConfigurationMethod method = binding.Methods["AddSslCertificate"];
ConfigurationMethodInstance mi = method.CreateInstance();
mi.Input.SetAttributeValue("certificateHash", certificateHash);
mi.Input.SetAttributeValue("certificateStoreName", certificateStore);
mi.Execute();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With