使用 Microsoft.Web.Administration 添加处理程序

Adding Handler with Microsoft.Web.Administration

我在初始应用程序设置期间使用以下代码注册 httpHandler。

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();
            }
        }
    }
    
    ...
}

问题

它正确地添加了处理程序并且处理程序也工作正常。但是有一个问题。 最初我的 web.config 看起来像这样

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

上面代码的效果应该是这样的

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

但是我得到了关注

注意 清除了处理程序并添加了所有从 IIS 服务器继承的处理程序(其中 72 个),然后在最后添加了我的处理程序。

问题

是否有可能以某种方式阻止 CommitChanges() 方法添加清除,然后将所有处理程序添加到本地 web.config

看来我需要多搜索一下。

this comment 中的 CarlosAg 说

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);

因此将 CEC.Add(ele) 更改为 CEC.AddAt(0, ele) 解决了问题