3

How can I use c# to programmatically change the SSL Settings feature for Default Web Site in IIS to require SSl? I know to use Server Manager from Microsoft.Web.Administration, but I don't know how to edit a feature, or if you can.

Edit: I'm not trying to change the application settings, but access the feature "SSL Settings". I could access the settings and change enabled protocol to https, but this will not do anything because in IIS https enables http as well, and vice versa. In order to only accept https requests, I need to access SSL settings and change it to require ssl.

NineBerry
  • 26,306
  • 3
  • 62
  • 93
Michael
  • 53
  • 4
  • Possible duplicate of [How to change settings of an application in IIS through C#](https://stackoverflow.com/questions/3532082/how-to-change-settings-of-an-application-in-iis-through-c-sharp) – Arian Motamedi Mar 29 '18 at 16:20

1 Answers1

1

You need to reference the assembly Microsoft.Web.Administration from your application as described in this answer.

You can then use the following code:

// Default website always has id 1
int defaultSiteId = 1;

// Get Server Manager
ServerManager serverManager = new ServerManager();

// Get default website (Always has id 1)
var defaultSite = serverManager.Sites.First(s => s.Id == defaultSiteId);

// Get reference to config file where host configuration is stored
Configuration config = serverManager.GetApplicationHostConfiguration();

// Get reference to the section that has the SSL settings for the website
ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", defaultSite.Name);

// Change the sslFlags to require ssl
// (See here for reference: https://learn.microsoft.com/en-us/iis/configuration/system.webServer/security/access )
accessSection.SetAttributeValue("sslFlags", "Ssl");

// Save and apply the changes
serverManager.CommitChanges();

The possible values for the sslFlags attribute are described at https://learn.microsoft.com/en-us/iis/configuration/system.webServer/security/access

NineBerry
  • 26,306
  • 3
  • 62
  • 93