C#从web.config

时间:2017-12-01 12:42:24

标签: asp.net web-config

我需要在WCF中读取customHeaders值。下面是我的应用程序的示例配置文件。我需要以编程方式找到" Access-Control-Allow-Origin"键。请帮助实现同样的目标。

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="X-Content-Type-Options" value="nosniff"/>
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200"/>
    <add name="Access-Control-Request-Method" value="POST,GET,PUT,DELETE,OPTIONS"/>
    <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type"/>
    <add name="Access-Control-Allow-Credentials" value="true"/>
  </customHeaders>
</httpProtocol>

我在下面尝试但是没有用。

Configuration config = serverManager.GetWebConfiguration("Web.Config");
ConfigurationSection httpProtocolSection = config.GetSection("system.webServer/httpProtocol");
ConfigurationElementCollection customHeadersCollection = httpProtocolSection.GetCollection("customHeaders");
foreach(var element in customHeadersCollection)
{
    Response.Write(element.Attributes[0].Name);
}

1 个答案:

答案 0 :(得分:1)

我从Microsoft找到了这个示例来读取这些值。

https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpprotocol/customheaders/#sample-code

您需要引用Microsoft.Web.Administration.dll才能访问这些类。

      using (ServerManager serverManager = new ServerManager())
      {
         Configuration config = serverManager.GetWebConfiguration("Default Web Site");
         ConfigurationSection httpProtocolSection = config.GetSection("system.webServer/httpProtocol");
         ConfigurationElementCollection customHeadersCollection = httpProtocolSection.GetCollection("customHeaders");

         // what you want is in customerHeadersCollection
      }