Search code examples
c#.netweb-confighandlerconfigurationmanager

C# check if handler is present in Web.Config


In my Web.Config file I have the following:

<system.webServer>
  <handlers>
    <add name="HANDLERNAME" verb="*" path="PATH.axd" type="HANDLERTYPE">
  </handlers>
</system.webServer>

Before I run a particular bit of code, I want to check to see if the handler is present in my Web.Config file.

Is this something I'm able to do?

I've tried: ConfigurationManager.GetSection("system.webServer/handlers") with no success, as this returns null.

Any help would be greatly appreciated!


Solution

  • I found two ways to check for the Handlers in the web.config

        XmlDocument doc = new XmlDocument();
        doc.Load(path); *//path is the location of the web.config file*
    
        XmlElement root = doc.DocumentElement;
        XmlNode nodes = root.SelectSingleNode("/system.webServer");
        XmlNodeList childnotes = nodes.ChildNodes;
        bool isExist = false;;
        foreach (XmlNode node in childnotes)
        {
            if (node.Name.Contains("handlers"))
            {
                isExist = node.OuterXml.Contains("HANDLERNAME");
            }
        }
    

    you can check the value of isExist

    The other way is to get the entire web.config as a string and check if it contains HANDLERNAME