2014-01-08 136 views
0

我开发了一个自定义模块,它使用httpmodules,当我的模块被卸载时,需要将其添加到web.config中,当我的模块被安装并从中移除时。到目前为止,我一直在做的是修改我的web.config文件,在安装模块后手动添加必要的部分,并在模块卸载之前将其删除。本节如下所示:以编程方式更改web.config

<httpModules> 
    <add type="QueryStringModule" name="QueryStringModule"/> 
</httpModules> 

现在我想知道它是否可以自动完成这一任务,即编程修改web.config。我已经Google搜索,但他们不适合我。有什么方法在asp.net中解决这个问题。谢谢。

回答

0

我不会建议你这样做。您为应用程序用户提供了许多权力。他们不应该被允许更改应用程序配置选项。如果这些是面向用户的配置设置,请考虑将它们放在数据库中。您还应该记住,用户帐户应具有访问文件系统中配置文件的适当权限(这使得它甚至更糟糕)。

不管怎样,也许这代码片段(更改应用程序设置)会帮助你做到这一点,如果你调整它:

Configuration myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); 
myConfiguration.AppSettings.Settings.Item("myKey").Value = ... 
myConfiguration.Save(); 

希望我帮助!

1

你可以做这样的事情:

using System.Web.Configuration; 

// ... 

var config = WebConfigurationManager.OpenWebConfiguration("/web.config"); 
var modules = config.GetSection("system.web/httpModules") as HttpModulesSection; 

另外,我觉得,这也能发挥作用(无需显式指定配置源):

using System.Configuration; 

// ... 

var modules = ConfigurationManager.GetSection("system.web/httpModules") as 
    HttpModulesSection; 

(虽然,在上面的代码需要添加对System.Configuration的引用)。

一旦您有HttpModulesSection的实例,请使用其Modules属性添加或删除模块。

希望这会有所帮助。

+0

当我用WebConfigurationManager.OpenWebconfiguration( “/的web.config”)或( “〜”)发生无效异常错误。它显示无法映射路径'/web.config'。错误信息。我也尝试过使用xml,但它也不起作用。对我有没有什么好的解决方案。 – haripds

+0

@haripds试试'WebConfigurationManager.OpenWebConfiguration(null)'([MSDN](http://msdn.microsoft.com/en-us/library/ms151456(v = vs.110).aspx)) – volpav

+0

最后问题是解决了。非常感谢。 – haripds

0
public class CustomSection : ConfigurationSection 
{ 
    public CustomSecuritySection Security { get; private set; } 
       [ConfigurationProperty("type", IsRequired = true, DefaultValue = "QueryStringModule")] 
     public String type 
     { 
     get { return (String)base["type"]; } 
     set { base["type"] = value; } 
     } 

     [ConfigurationProperty("name", IsRequired = true, DefaultValue = "QueryStringModule")] 
    public String name 
    { 
    get { return (String)base["name"]; } 
    set { base["name"] = value; } 
    } 

    public CustomSection() 
    { 

    } 
    }     

 Configuration config = ConfigurationManager.OpenExeConfiguration(@"D:\xxxxx\xxxx\web.config"); 
     //var httpmod = config.Sections.Add("TestSecton", 

     if (config.Sections["NewSection"] == null) 
     { 
     customSection = new CustomSection(); 
     config.Sections.Add("NewSection", customSection); 
     config.Save(ConfigurationSaveMode.Full); 
     //ConfigurationManager.RefreshSection("NewSection"); 
     }