我的 Web 应用程序使用外部类库来执行我在许多地方使用的某些过程。我想添加到我的库中的一件事是这个配置器类,它允许我加密 web.config 文件的部分内容。
现在,我从 global.asax
调用该类,它进行编译,并且智能感知没有任何问题,但在执行 Web 应用程序时收到此错误:
Request is not available in this context
如何解决这个问题?
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>
最佳答案
David Hoerster 是对的,Request
尚未初始化,因此会出错。如果您只需要访问根配置,则可以使用:
webconfig = WebConfigurationManager.OpenWebConfiguration("~");
关于c# - 通过global.asax从外部类获取web.config请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16159169/