在web.config的重写部分中读取键值对

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在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;
        }

    }

以上是关于在web.config的重写部分中读取键值对的主要内容,如果未能解决你的问题,请参考以下文章

Hadoop:Shuffle组件

如何定义具有潜在子元素和属性的属性的自定义 web.config 部分?

URL 重写 - web.config 错误

usage memcache in linux

如何在 Flutter 中创建和读取一组键值对(映射)以在 Firestore 中存储数据

文件中存在重复键值对时如何读取属性文件?