无法动态添加web.config中的新规则

时间:2013-08-17 06:12:11

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

我在我的应用程序中应用了url rewrite,并在web.config中添加了一些规则

<modulesSection>
    <rewriteModule>
      <rewriteOn>true</rewriteOn>
      <rewriteRules>
         <rule source="About/About-Demo" destination="About/Demo.aspx"/>
      </rewriteRules>
      </rewriteModule>
</modulesSection>

现在我想从代码中添加新规则。我使用了以下代码......

public void NEWTEST(string source, string destination)
{       
    XDocument xml = XDocument.Load( Path.Combine( Server.MapPath("~").ToString(), "web.config"));


    if (!RuleExists(source, destination))
    {  
        XElement elem = new XElement("rule");
        elem.SetAttributeValue("source", source);
        elem.SetAttributeValue("destination", destination);
        xml.Element("rewriteRules").Add(elem); // Error occured
        xml.Save(Path.Combine( Server.MapPath("~").ToString(), "web.config"));
    }
}


public  bool RuleExists(string source, string destination)
    {
        XDocument doc = XDocument.Load(Path.Combine(Server.MapPath("~").ToString(), "web.config"));

        return doc.Descendants("rewriteRules").Elements()
                  .Where(e => e.Attribute("source").Value == source
                  && e.Attribute("destination").Value == destination).Any();
    }

但是在“xml.Element(”rewriteRules“)行。添加(elem); //发生错误”我收到错误 “System.NullReferenceException:对象引用未设置为对象的实例。” 请给我解决方案。这是创建新规则的正确方法,如果没有,那么请给我正确的方法来做到这一点。提前预测

2 个答案:

答案 0 :(得分:0)

我不确定使用xml来修改配置文件是否可行。这是为我们制定的Click Here

有预定义的类来执行此操作。检查一下

答案 1 :(得分:0)

以下代码为我工作..

 public bool RuleExists(string source, string destination)
{
    XDocument doc = XDocument.Load(Path.Combine(Server.MapPath("~").ToString(), "web.config"));

    return doc.Descendants("rewriteRules").Elements()
              .Where(e => e.Attribute("source").Value == source
              && e.Attribute("destination").Value == destination).Any();
}
public void DefineUrlRewrite(string source, string destination)
{
    XDocument xml = XDocument.Load(Path.Combine(Server.MapPath("~").ToString(), "web.config"));


    if (RuleExists(source, destination))
    {
        //element is already in the config file
        //do something...
        lblMsg.Text = "This Rule is already exists, choose another one!!! <br/>";
    }
    else
    {
        XElement elem = new XElement("rule");
        elem.SetAttributeValue("source", source);
        elem.SetAttributeValue("destination", destination);

        xml.Descendants("rewriteRules").First().Add(elem);
        xml.Save(Path.Combine(Server.MapPath("~").ToString(), "web.config"));
    }
}