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

标签 c# web-config global-asax

我的 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/

相关文章:

c# - 如何在生产中捕获 HttpRequestValidationException

c# - 当 access_token 长度超过约 2000 个字符时,SignalR 在连接时返回 404 -

C#,无法将类型 `long' 隐式转换为 `uint'

c# - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。因此不允许访问 Origin 'http://www.sitename.com,'

visual-studio-2008 - 从源代码管理中忽略 Web.Config,而不从 VS 2008 中的项目中排除

asp.net - 你能运行一个 "service"来运行来自 ASP.Net 项目的计划任务吗?

caching - 在.net Web应用程序中加载高度重复使用的数据的最佳方法是什么

C# : Thread Workload and Memory useage

c# - 使用表达式/lambda 设置属性值的通用方法

asp.net-mvc - 注册通用页面基类