【问题标题】:Read values of web.config file读取 web.config 文件的值
【发布时间】:2017-09-14 12:09:18
【问题描述】:

我想读取 web.config 文件不同部分的值。

例如

<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" requestValidationMode="4.5" 
maxRequestLength="102400" />
<pages validateRequest="true"></pages>
</system.web>

在这个 system.web 部分我想阅读 httpRuntime requestValidationMode 价值。在页面中,我想读取 validateRequest 的值。

另外,我想读取自定义标题的值

 <httpProtocol>
  <customHeaders>
    <add name="X-Content-Type-Options" value="nosniff" />
    <add name="X-Frame-Options" value="SAMEORIGIN" />
    <remove name="X-Powered-By" />
    <add name="X-XSS-Protection" value="1; mode=block" />
  </customHeaders>
</httpProtocol>

【问题讨论】:

    标签: asp.net-mvc iis c#-4.0 iis-7 web-config


    【解决方案1】:

    我相信你想要这样的东西

    ConfigurationSection httpProtocolSection = 
        ConfigurationManager.GetSection("system.webServer/httpProtocol");
    ConfigurationElementCollection customHeadersCollection = httpProtocolSection.GetCollection("customHeaders");    
    

    对于其他值,您必须搜索该值的存储位置。例如

    <compilation debug="true" ...>
    

    存储在这里

    HttpContext.Current.IsDebuggingEnabled
    

    此外,许多节类型都存储在 System.Web.Configuration 中

    System.Web.Configuration.PagesSection
    System.Web.Configuration.HttpHandlersSection
    

    您也可以使用 GetSection() 检索那些。

    【讨论】:

    • var customHeaders = (AppSettingsSection)ConfigurationManager.GetSection("customHeaders") 和 var customHeaders = ConfigurationManager.GetSection("customHeaders") as NameValueCollection 都返回空值。
    • 我编辑了它,我意识到您需要该部分的 XPath。
    • 我正在 global.asax.cs 中编写此代码。我想阅读 web.config 文件并验证它
    • 啊。我误解了这一点。然后您需要 ConfigurationManager 类。最终修改已应用。
    • 仍然返回空值
    猜你喜欢
    • 2012-10-13
    • 2015-11-27
    • 1970-01-01
    • 2015-07-03
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多