'How can i create a website in IIS and bind a certificate from the store using c#?

I am trying to create a website in IIS using a certificate from the Store but get the error: A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)

I am creating the website with code below:

Certificate is retrieved from this code and passed to the bottom code:

        X509Store store = new X509Store(StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
        X509Certificate2Collection scollection = X509Certificate2UI.SelectFromCollection(fcollection, "Certificate Select", "Select a certificate from the following list to get information on that certificate", X509SelectionFlag.SingleSelection);
        var storeCertificate = scollection.Count > 0 ? scollection[0] : null;
        
        
        
        
        
        using (ServerManager iisManager = new ServerManager())
        {

            ServerManager serverManager = new ServerManager();                    
            X509Certificate2 certificate = null;
            if (storeCertificate != null)  
            {
                certificate = new X509Certificate2(storeCertificate);                        
                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
                store.Remove(certificate);                  
                store.Add(certificate);
                store.Close();
                Site website = iisManager.Sites.Add(name.ToString(), $"*:{port}:", location, certificate.GetCertHash());
                website.Applications[0].ApplicationPoolName = appPoolName;
                website.ServerAutoStart = true;
                iisManager.CommitChanges();
            }
        }


Solution 1:[1]

You may need to export the certificate to a file, then load it into an X509Certificate2 object, then add to the store, and finally set the bind.

Export the certificate to a file:

File.WriteAllBytes(filePath, cert.Export(X509ContentType.Pkcs12, password))

Then import this certificate file into the store by doing the following:

var cert = new X509Certificate2(certFilePath, certPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

// My original AddCertToStore function
AddCertToStore(cert, StoreName.My, StoreLocation.LocalMachine, "Friendly Name"); 

Finally set the bindings as before.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JennyDai