簡體   English   中英

在web.config的重寫部分中讀取鍵值對

[英]Reading the key value pairs in a rewrite section of web.config

我有一個名為RedirectMapping.config的重定向映射文件。 它具有以下格式:

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

該文件在我的web.config文件中指向如下:

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

我需要在運行時從RedirectMapping.config文件中讀取鍵值對。 .Net中怎么可能? 是否有可用的API來做,還是我必須制作這樣的API?

我將配置文件作為XML文檔讀取,並提取了鍵值對。 這是代碼:

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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM