0

我在我的应用程序中应用了 url 重写,并在 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").Add(elem); // 发生错误”行,我收到错误“System.NullReferenceException:对象引用未设置为对象的实例。”。请给我解决方案。这是创建新规则的正确方法吗?如果不是,那么请提前给我正确的方法来执行此操作。thanxx

4

2 回答 2

0

我不确定使用 xml 修改配置文件是否可行。这是为我们解决的问题点击这里

有预定义的类可以做到这一点。检查他们

于 2013-08-17T08:16:59.220 回答
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"));
    }
}
于 2013-09-21T12:59:17.923 回答