bgm*_*der 2 c# web-config global-asax
我的Web应用程序将外部类库用于我在许多地方使用的某些过程。我想添加到库中的一件事是此配置程序类,该类允许我加密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();
}
}
Run Code Online (Sandbox Code Playgroud)
该类在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>
Run Code Online (Sandbox Code Playgroud)
大卫·霍斯特(David Hoerster)是对的,Request还没有初始化,所以它会出错。如果只需要访问根配置,则可以使用:
webconfig = WebConfigurationManager.OpenWebConfiguration("~");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
599 次 |
| 最近记录: |