以编程方式更改IIS网站的SSL设置

问题描述 投票:2回答:1

如何使用c#以编程方式更改IIS中的默认网站的SSL设置功能以要求SSl?我知道要使用Microsoft.Web.Administration的服务器管理器,但我不知道如何编辑功能,或者如果可以的话。

编辑:我不是要更改应用程序设置,而是访问“SSL设置”功能。我可以访问设置并将启用的协议更改为https,但这不会做任何事情,因为在IIS中,https也会启用http,反之亦然。为了只接受https请求,我需要访问SSL设置并将其更改为要求ssl。

c# ssl iis
1个回答
1
投票

您需要从Microsoft.Web.Administration中描述的应用程序中引用程序集this answer

然后,您可以使用以下代码:

// 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://docs.microsoft.com/en-us/iis/configuration/system.webServer/security/access )
accessSection.SetAttributeValue("sslFlags", "Ssl");

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

sslFlags描述了https://docs.microsoft.com/en-us/iis/configuration/system.webServer/security/access属性的可能值

© www.soinside.com 2019 - 2024. All rights reserved.