IIS7 programmatically modify application anonymous access

2

I'm trying to enable anonymous access on an application in IIS7, using the code below:

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

However I'm getting this error:

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

How can I modify anonymous access for the application?

Thanks, ng93

c#
iis
iis-7
anonymous-access
asked on Stack Overflow Nov 18, 2013 by ng93

1 Answer

1

The code above is invalid since the section is locked at ApplicationHost.config level for security reasons. In the code you are trying to use it is trying to set it in Web.config. If you really wanted that you would first need to request it from a GetApplicationHost call set the overrideMode and then get the section again from a GetWebConfiguration. But all in all I would still recommend instead setting that value at the server level so that it cannot be accidentally changed in web.config by a deployment or some other mechanism.

So to do that I would instead recommend doing:

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();
}
answered on Stack Overflow Nov 18, 2013 by Carlos Aguilar Mares • edited May 20, 2015 by Yuval Itzchakov

User contributions licensed under CC BY-SA 3.0