IIS7以编程方式修改应用程序匿名访问

时间:2013-11-18 16:25:53

标签: c# iis iis-7 anonymous-access

我正在尝试使用以下代码在IIS7中启用对应用程序的匿名访问:

ConfigurationSection config = server.GetWebConfiguration(webSiteName).GetSection("system.webServer/security/authentication/anonymousAuthentication", "/" + applicationName);
config.OverrideMode = OverrideMode.Allow;
config["enabled"] = true;

但是我收到了这个错误:

Failed: The request is not supported. (Exception from HRESULT: 0x80070032)

如何修改应用程序的匿名访问?

谢谢, ng93

1 个答案:

答案 0 :(得分:1)

上面的代码无效,因为出于安全原因,该部分已在ApplicationHost.config级别锁定。在您尝试使用它的代码中尝试在Web.config中设置它。如果您真的想要首先需要从GetApplicationHost调用请求它,请设置overrideMode,然后再从GetWebConfiguration获取该部分。但总而言之,我仍然建议在服务器级别设置该值,以便不能通过部署或其他机制在web.config中意外更改它。

所以要做到这一点我会建议做:

string webSiteName = "Default Web Site";
string applicationName = "MyApp";

using (ServerManager server = new ServerManager())
{
    ConfigurationSection config = server.GetApplicationHostConfiguration()
                                        .GetSection(@"system.webServer/security/
                                                     authentication/
                                                     anonymousAuthentication", 
                                                     webSiteName + "/" + applicationName);
    config.OverrideMode = OverrideMode.Allow;
    config["enabled"] = true;
    server.CommitChanges();
}