我有一个名为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?
答案 0 :(得分:0)
我将配置文件作为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;
}
}