【问题标题】:How to read a section from web.config on IIS7 w/ .net 4 in C#如何在 C# 中使用 .net 4 从 IIS7 上的 web.config 中读取一个部分
【发布时间】:2011-02-23 23:02:56
【问题描述】:

我的 web.config 中有以下部分:

<system.webServer>
    <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="0.00:00:30" />

        <remove fileExtension=".ogv" />
        <mimeMap fileExtension=".ogv" mimeType="video/ogg" />

        <remove fileExtension=".webm" />
        <mimeMap fileExtension=".webm" mimeType="video/webm" />

        <!-- and a bunch more... -->
    </staticContent>
    <!-- ... -->
</system.webServer>

这是我在伪代码中尝试做的事情:

var ext = ".ogg";
var staticContentElements = GetWebConfig().GetSection("system.webServer/staticContent").ChildElements;
var mimeMap = staticContentElements.Where(c =>
                   c.GetAttributeValue("fileExtension") != null && 
                   c.GetAttributeValue("fileExtension").ToString() == ext
               ).Single();

var mimeType = mimeMap.GetAttributeValue("mimeType").ToString();

基本上,我需要通过 fileExtension 搜索 mimeMaps 并获取它们的 mimeType。

【问题讨论】:

    标签: c# .net linq iis-7 web-config


    【解决方案1】:

    您需要create a custom configuration section 才能获得该信息。

    【讨论】:

      【解决方案2】:

      George Stocker 的 answer 将我带到了 Google 搜索["staticContent" custom configuration section],这将我带到了一篇名为 Adding Static Content MIME Mappings <mimeMap> 的 iis.net 文章。

      这篇文章让我想到了:

      using (var serverManager = new ServerManager())
      {
          var siteName = HostingEnvironment.ApplicationHost.GetSiteName();
          var config = serverManager.GetWebConfiguration(siteName);
          var staticContentSection = config.GetSection("system.webServer/staticContent");
          var staticContentCollection = staticContentSection.GetCollection();
      
          var mimeMap = staticContentCollection.Where(c =>
              c.GetAttributeValue("fileExtension") != null &&
              c.GetAttributeValue("fileExtension").ToString() == ext
          ).Single();
      
          var mimeType = mimeMap.GetAttributeValue("mimeType").ToString();
          contentType = mimeType.Split(';')[0];
      }
      

      这对我来说非常有效。我只需要在这里和那里添加一些null 支票就可以了。

      【讨论】:

        猜你喜欢
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-10
        • 2011-03-01
        • 1970-01-01
        • 2011-03-17
        相关资源
        最近更新 更多