2013-04-23 39 views
1

我的web應用程序使用外部類庫來執行某些在許多地方使用的過程。我想添加到我的庫中的一件事是這個配置器類允許我加密我的web.config文件的一部分。現在通過global.asax從外部類獲取web.config請求

,我打電話從global.asax類,它編譯和智能感知沒有任何問題,但在web應用的執行正在此錯誤:

請求不在可用這方面

我該如何解決這個問題?

public class configurator { 
private Configuration _webconfig; 
public const string DPAPI = "DataProtectionConfigurationProvider"; 

public Configuration webconfig { 
    get { return _webconfig; } 
    set { _webconfig = webconfig; } 
} 

public configurator() { 
    webconfig = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath); 
} 

public void ProtectSection(string sectionName, string provider = DPAPI) { 
    ConfigurationSection section = webconfig.GetSection(sectionName); 

    if (section != null && !section.SectionInformation.IsProtected) { 
     section.SectionInformation.ProtectSection(provider); 
     webconfig.Save(); 
    } 
} 

public void EncryptConnString(string protectionMode) { 
    ConfigurationSection section = webconfig.GetSection("connectionStrings"); 
    section.SectionInformation.ProtectSection(protectionMode); 
    webconfig.Save(); 
} 

public void DecryptConnString() { 
    ConfigurationSection section = webconfig.GetSection("connectionStrings"); 
    section.SectionInformation.UnprotectSection(); 
    webconfig.Save(); 
} 
} 

的類被稱爲第一件事就是在Global.asax (遺憾的混合;我更喜歡C#,但在VB啓動其他項目之前,我開始用C#!)

<%@ Application Language="VB" %> 
<script runat="server"> 
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) 
    ' Code that runs on application startup - this will encrypt the web.config 
    Dim thisconfigurator As mydll.configurator = New orsus.configurator() 
    If ConfigurationManager.AppSettings("con") = "production" Then 
     thisconfigurator.ProtectSection("AppSettings") 
     thisconfigurator.ProtectSection("connectionStrings") 
     thisconfigurator.ProtectSection("system.net/mailSettings/smtp") 
    End If 
End Sub 
</script> 
+0

在global.asax中的哪個點你調用它? – 2013-04-23 01:00:50

+0

我在Application_Start子內調用它的第一件事。 – bgmCoder 2013-04-23 01:01:40

回答

4

David Hoerster是對的,Request尚未初始化,所以它會出錯。如果你只需要訪問root配置,這可以工作:

webconfig = WebConfigurationManager.OpenWebConfiguration("~");