Search code examples
c#iishttpsssl-certificateself-signed

How to Enable HTTPS in IIS using C#?


Programmatically (C#) I want to configure IIS site in https. I have created a self-signing certificate and manually configured the site. But I want to automate this process using C#. I can't find a proper solution anywhere. Can someone help me with this?


Solution

  • Finally, I got the solution. This is the code i wanted.

    ServerManager serverManager = new ServerManager();
    Site mySite = serverManager.Sites.Add(siteName.ToString(), "http", "*:80:" + domainName, physicalPath);
    
    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);                
    store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);                
    X509Certificate2 certificate = new X509Certificate2("SSL server certificate", "password", X509KeyStorageFlags.Exportable);                
    store.Add(certificate);      
    
    var binding = mySite.Bindings.Add("*:443:" + domainName, certificate.GetCertHash(), "My");                
    binding.Protocol = "https";                
    mySite.ApplicationDefaults.ApplicationPoolName = siteName;                
    serverManager.CommitChanges();                
    store.Close();