【发布时间】:2013-04-23 00:59:09
【问题描述】:
我的 Web 应用程序对我在许多地方使用的某些过程使用外部类库。我想添加到我的库中的一件事是这个配置器类,它允许我加密我的 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#,但在我开始使用 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>
【问题讨论】:
-
你在 global.asax 的什么时候调用这个?
-
我在 Application_Start 子中首先调用它。
标签: c# web-config global-asax