2017-09-14 74 views
0

我想读取web.config文件不同部分的值。读取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> 

回答

0

我相信你想是这样的

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( )以及。

+0

VAR customHeaders =(AppSettingsSection)ConfigurationManager.GetSection( “customHeaders”)和 VAR customHeaders = ConfigurationManager.GetSection( “customHeaders”)作为NameValueCollection中 两者都返回空值。 – ABB

+0

我编辑它,我意识到你需要该部分的XPath。 –

+0

我在global.asax.cs中写这段代码。我想要读取web.config文件并验证它 – ABB