2014-01-08 137 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"); 
     }