View Complete Thread
  • Re: Installing SSL for Custom Domains in IIS using LetsEncrypt

    Sep 24, 2019 02:16 PM|danimalik54|LINK

    Hey,
    I am switching the approach and now going to add the bindings, here is what the other i am facing.

    I have an Application hosted in IIS website "TestWebsite" and i am using Microsoft.Web.Administration for IIS Automation.

    I have to do following operations with bindings of the SAME website "TestWebsite" from "TestWebsite"

    1. Add HTTPS binding with SSL certificate to the website "TestWebsite" from same application (code to add binding will be in same "TestWebsite")
    2. Remove the Binding.

    I have done the following code and weird thing is that on localhost it is adding the https binding but even before manager.commitchange(). This line throw exception on local host, so i removed this line but on Windows Server its not adding the binding even after successfully running the code. (without commitchanges(),  i hv no idea how its working on localhost without it)

    using (ServerManager iisManager = new ServerManager())
    {
    	var website = iisManager.Sites.Where(x => x.Name == "TestWebsite").FirstOrDefault();
    	if (website != null)
    	{
    		var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
    		store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
    		var pfxPath = Server.MapPath(model.PfxPath);
    		var certificate = new X509Certificate2(pfxPath, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
    		store.Add(certificate);
    		store.Close();
    		var certHash = certificate.GetCertHash();
    
    		string bindingInformation = string.Format("{0}:{1}:{2}", "*", "443", model.UserCustom);
    		var binding = website.Bindings.Add(bindingInformation, certHash, store.Name);
    		binding.Protocol = "https";
    		store.Close();
    
    		website.ApplicationDefaults.EnabledProtocols = "http,https";
    		iisManager.CommitChanges();
    	}
    }
    

    I receive following errors.

    1- A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)

    Is there some permission related error? What i am doing wrong in it?

    Your help will be appreciated

    Thank you  :)

    Danial Malik :)