0

I have a redirect mapping file called RedirectMapping.config. It has the following format:

<rewriteMaps>
    <rewriteMap name = "StaticRedirects">
       <add key="/newsstand/" value="/publications/articles/" />
       <add key="/careers/" value="/careers/business-professionals/" />
    </rewriteMap>
 </rewriteMaps>

This file is pointed to in my web.config file as follows:

<system.webServer>
  <rewrite>
      <rewriteMaps configSource="RedirectMapping.config"/>
      <rules>  
        <rule name="Redirect rule">  
          <match url=".*" />  
          <conditions>  
            <add input="{StaticRedirects: {SCRIPT_NAME}}" pattern="(.+)" />  
          </conditions>  
          <action type="Redirect" url="http://localhost{C:1}" appendQueryString="false" redirectType="Permanent"/>  
        </rule>  
      </rules>  
    </rewrite>
  </system.webServer>

I need to read the key value pairs from the RedirectMapping.config file at the run time. How is this possible in .Net? Is there any API available to do it or I have to make such API?

Payam
  • 741
  • 3
  • 14
  • 37
  • You can read it as an xml file. see https://stackoverflow.com/questions/9733635/how-to-read-web-config-section-as-xml-in-c – Aman B Feb 24 '18 at 18:05
  • @AmanB yes, I know that. I will do that as the last resort. I was hopeful that there is a clean API that I can quickly read the rerwriteMap key, values, but my research for the past 2 days has turned in nothing. – Payam Feb 24 '18 at 19:13

1 Answers1

0

I read the config file as an XML document and extracted the key value pairs. Here is the code:

public static class ReWriteProcessor
    {
        public static Dictionary<string, string> MapedUrls { get;}

        static ReWriteProcessor()
        {
            MapedUrls = GetKeyValuePairs();
        }


        private static Dictionary<string,string> GetKeyValuePairs()
        {
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            XDocument doc = XDocument.Load(WolfAppData.ReWriteMapFile);
            if (doc.Descendants().Any())
            {
                var elements = doc.Descendants("rewriteMap").Elements().ToList();
               foreach (XElement element in elements)
                {
                   string key =   element.FirstAttribute.Value;
                    string value = element.LastAttribute.Value;
                    if(!keyValues.ContainsKey(key))
                        keyValues.Add(key,value);
                }
            }

            return keyValues;
        }

    }
Payam
  • 741
  • 3
  • 14
  • 37