public static void RegisterRedirectHandler(this EditableXmlConfigHelper configHelper, string name, string redirectHandlerPath, string fullTypeName) { // Because the "system.webServer" ConfigurationSection is an IgnoreSection, it must be modified // using the raw XML. ConfigurationSection webServerSection = configHelper.Configuration.GetSection(ConfigHelperExtensions.WebServerSectionName); if (webServerSection == null) { webServerSection = new IgnoreSection(); configHelper.Configuration.Sections.Add(ConfigHelperExtensions.WebServerSectionName, webServerSection); } XElement webServerElement; string webServerSectionRawXml = webServerSection.SectionInformation.GetRawXml(); if (webServerSectionRawXml == null) { webServerElement = new XElement(ConfigHelperExtensions.WebServerSectionName); } else { webServerElement = XElement.Parse(webServerSectionRawXml); } XElement handlersElement = webServerElement.Element("handlers"); if (handlersElement == null) { handlersElement = new XElement("handlers"); webServerElement.Add(handlersElement); } XElement addElement = handlersElement.Elements("add") .FirstOrDefault(e => { XAttribute attr = e.Attribute("type"); return attr != null && attr.Value == fullTypeName; }); if (addElement == null) { addElement = new XElement("add", new XAttribute("name", name), new XAttribute("verb", "GET"), new XAttribute("path", redirectHandlerPath), new XAttribute("type", fullTypeName)); handlersElement.Add(addElement); } webServerSection.SectionInformation.SetRawXml(webServerElement.ToString()); }
/// <summary> /// Retrieves or creates the system.webServer section /// </summary> /// <remarks> /// This section self initializes to empty xml, so if we detect that condition, /// we initialize it to empty but valid xml so that it can be manipulated. /// </remarks> /// <returns>The existing or new system.webServer section.</returns> public IgnoreSection GetOrCreateSystemWebServerSection() { // This section has no strongly typed equivalent, so we treat it only as an IgnoreSection IgnoreSection webServerSection = this._configuration.GetSection(SystemWebServerSectionName) as IgnoreSection; if (webServerSection == null) { webServerSection = new IgnoreSection(); this._configuration.Sections.Add(SystemWebServerSectionName, webServerSection); } // Detect empty xml and initialize it to legal empty state if found. // We do this to simplify the logic of parsing it and adding new sections. SectionInformation sectionInformation = webServerSection.SectionInformation; string rawXml = sectionInformation.GetRawXml(); if (string.IsNullOrEmpty(rawXml)) { rawXml = "<" + SystemWebServerSectionName + "/>"; sectionInformation.SetRawXml(rawXml); } return webServerSection; }