通过global.asax从外部类获取web.config请求

时间:2013-04-23 00:59:09

标签: c# web-config global-asax

我的网络应用程序使用外部类库来处理我在许多地方使用的某些过程。我想添加到我的库中的一件事是这个配置器类,允许我加密我的web.config文件的一部分。

现在,我从global.asax调用该类,它编译,并且intellisense没有任何问题,但是在执行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#,但在开始使用c#之前在vb中启动了另一个项目!)

<%@ 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>

1 个答案:

答案 0 :(得分:4)

David Hoerster是对的,Request尚未初始化,因此会出错。如果您只需要访问根配置,则可以:

webconfig = WebConfigurationManager.OpenWebConfiguration("~");
相关问题