Adding Handler with Microsoft.Web.Administration

140 Views Asked by At

I use following code to register httpHandler during initial application setup.

class SomeHandler: IHttpAsyncHandler {

    public void Register() {
        using (ServerManager serverManager = new ServerManager()) {

            string SITE_NAME = HostingEnvironment.ApplicationHost.GetSiteName();
            string APP_PATH = HostingEnvironment.ApplicationHost.GetVirtualPath();
            string SERVICE_CLASS = GetType().FullName.ToString();
            string HANDLER_NAME = GetType().Name;

            ConfigurationElementCollection CEC = serverManager
                .GetWebConfiguration(SITE_NAME, APP_PATH)
                .GetSection("system.webServer/handlers")
                .GetCollection();

            ConfigurationElement ele = null;
            foreach (ConfigurationElement ele1 in CEC) {
                if (ele1.Attributes["name"].Value.ToString() == HANDLER_NAME) {
                    ele = ele1;
                }
            }
            if (ele == null) {
                ele = CEC.CreateElement("add");
                ele["name"] = HANDLER_NAME;
                ...
                CEC.Add(ele);
                serverManager.CommitChanges();
            }
        }
    }
    
    ...
}

Problem

It adds the handler correctly and handler works fine too. However there is an issue. Initially my web.config looks like this

<configuration>
    <appSettings />
    <system.webServer>
        <handlers>
        </handlers>
        ...
    </system.webServer>
    <system.web>
    ...
    </system.web>
</configuration>

The desired effect of code above should be as following

<configuration>
    <appSettings />
    <system.webServer>
        <handlers>
            <add name="SomeHandler" path="..." verb="..." type="NameSpace.SomeHandler" />
        </handlers>
        ...
    </system.webServer>
    <system.web>
    ...
    </system.web>
</configuration>

But instead I get following

issue with adding handler

Note that handlers are cleared and all the inherited handlers from IIS server (72 of them) added then my handler is added at the end.

Question

Is it possible to somehow stop CommitChanges() method from adding clear and then all the handlers to local web.config?

1

There are 1 best solutions below

0
AaA On BEST ANSWER

Seems like I needed a little more search.

CarlosAg in this comment says

Since this collection is a "mergeAppend='false'" collection it has that behavior of adding elements at the bottom and having to bring all of the parent ones to ensure semantics are correct.

To have the semantic of adding yours at the top (and prevent the parent ones to be copied) just change the line:

handlersCollection.Add(addElement);

to be:

handlersCollection.AddAt(0, addElement);

Thus changing CEC.Add(ele) to CEC.AddAt(0, ele) fixed the problem