以编程方式将规则添加到 Web.Config (system.webServer.rewrite.rules).rule name= "IP Blocking" 节点



我正在使用UrlRewrite规则来阻止Bots和Trolls。

目前,通过IIS或编辑Web添加条目是一个手动任务。配置文件。

我想添加一个规则到:(system.webServer.rewrite.rules).rule name="IP Blocking"如果我通过WinForms应用程序读取IIS日志文件来监控高容量流量,则节点。

Web。配置项可能如下所示:

<rewrite>
<rules>
<rule name="IP Blocking" stopProcessing="true">
<match url="(.*)" ignoreCase="false" />
<conditions logicalGrouping="MatchAny">
<add input="{REMOTE_ADDR}" pattern="0.0.0.0" />
<add input="{HTTP_X_Forwarded_For}" pattern="0.0.0.0" />
</conditions>
<action type="AbortRequest" />
</rule>
</rules>
</rewrite>

我开始查看'ConfigurationManager'来编辑和保存Web.config:

ConfigurationManager config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = path }, ConfigurationUserLevel.None);
ConfigurationSection WebServer = config.GetSection("system.webServer");

或:

ConfigurationFileMap fileMap = new ConfigurationFileMap(path);
Configuration config = WebConfigurationManager.OpenMappedMachineConfiguration(fileMap);

似乎没有办法访问/edit: 'system。

我的目标是拥有网络。以编程方式编辑和保存config .

这种方法似乎有无穷无尽的问题!

  • ConfigurationManager
  • WebConfigurationManager

每个人都报告了它的问题!

我最终使用了简单的XML方法:

// Instantiate XmlDocument:
XmlDocument doc = new XmlDocument();
// Load XML from the Web.config file:
doc.Load("Config/Web.config");
// Get the Rules Nodes:
XmlNodeList Rules = doc.SelectNodes("/configuration/system.webServer/rewrite/rules/rule");
// Loop through the Rules:
foreach (XmlNode Rule in Rules)
{
// Get the Name:
XmlAttribute NodeName = Rule.Attributes["name"];
// Check we have the correct Node:
if (NodeName.Value == "IP Blocking")
{
// Grab the Conditions Node:
XmlNode Conditions = Rule.SelectNodes("conditions").Item(0);
Conditions = Rule.SelectNodes("conditions").Item(0);
// Create the 'REMOTE_ADDR' Element:
XmlElement Element = doc.CreateElement("add");
Element.SetAttribute("input", "{REMOTE_ADDR}");
Element.SetAttribute("pattern", "XXX.XXX.XXX.XXX");
// Append the Element to the 'Conditions' Node:
Conditions.AppendChild(Element);
// Create the 'HTTP_X_Forwarded_For' Element:
Element = doc.CreateElement("add");
Element.SetAttribute("input", "{HTTP_X_Forwarded_For}");
Element.SetAttribute("pattern", "XXX.XXX.XXX.XXX");
// Append the Element to the 'Conditions' Node:
Conditions.AppendChild(Element);
}
}
// Save to Disk:
doc.Save(...

似乎。net开始有点被微软和其他公司忽视了!

当然,上面的代码给了我:

<rewrite>
<rules>
<rule name="IP Blocking" stopProcessing="true">
<match url="(.*)" ignoreCase="false" />
<conditions logicalGrouping="MatchAny">
<add input="{REMOTE_ADDR}" pattern="XXX.XXX.XXX.XXX" />
<add input="{HTTP_X_Forwarded_For}" pattern="XXX.XXX.XXX.XXX" />
</conditions>
<action type="AbortRequest" />
</rule>
</rules>
</rewrite>

相关内容

最新更新