【问题标题】:Reading the key value pairs in a rewrite section of web.config在 web.config 的重写部分中读取键值对
【发布时间】:2018-08-04 01:55:29
【问题描述】:

我有一个名为 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 文件读取。见stackoverflow.com/questions/9733635/…
  • @AmanB 是的,我知道。我会这样做作为最后的手段。我希望有一个干净的 API 可以快速读取 rerwriteMap 键、值,但我过去 2 天的研究一无所获。

标签: c# asp.net .net iis web-config


【解决方案1】:

我将配置文件作为 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;
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多