How can I add a HttpModule in ApplicationHost.config for all websites on IIS Server from C#?

418 views Asked by At

I am trying something like

  public string[] RegisterInApplicationConfig()
    {
        using (ServerManager serverManager = new ServerManager())
        {
            Configuration config = serverManager.GetApplicationHostConfiguration();
            var section = config.GetSection("location/system.webServer/modules");

        }
    }

but error I am getting is -

The configuration section location/system.webServer/modules cannot be read because it is missing a section declaration.

I am referring post from to add HttpModule -

How do I register a HttpModule in the machine.config for IIS 7?

So Basically in ApplicationHostConfig I need to get to

<location path="" overrideMode="Allow">
    <system.webServer>

    <modules>
        <add name="IsapiFilterModule" lockItem="true" />
1

There are 1 answers

0
Bit_Pulse On BEST ANSWER

So I found the solution after some hit & trials. Might help someone in future-

I needed to do GetCollection on "system.webServer/modules" section

 Configuration config = serverManager.GetApplicationHostConfiguration();
            var section = config.GetSection("system.webServer/modules", "");
            var collection = section.GetCollection();
            var element = collection.CreateElement();
            element.Attributes["name"].Value = "MyHttpModule";
            element.Attributes["type"].Value = MyHttpModule.XXXModule, MyHttpModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bc88fbd2dc8888795";
            collection.Add(element);
            serverManager.CommitChanges();