C# 如何在C中从IIS7 w/.net 4上的web.config读取节#

C# 如何在C中从IIS7 w/.net 4上的web.config读取节#,c#,.net,linq,iis-7,web-config,C#,.net,Linq,Iis 7,Web Config,我的web.config中有以下部分: <system.webServer> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="0.00:00:30" /> <remove fileExtension=".ogv" /> <mimeMap fileExtension=".ogv"

我的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>
基本上,我需要通过文件扩展名搜索mimaps并获取它们的mimeType。

你需要获得这些信息。

乔治·斯托克带领我在谷歌上搜索
[“staticContent”自定义配置部分]
,这让我看到了一篇名为的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
检查,就可以了

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];
}