开发者

How to read a section from web.config on IIS7 w/ .net 4 in C#

开发者 https://www.devze.com 2023-02-13 14:37 出处:网络
I\'ve got the following section in my web.config: <system.webServer> <staticContent> <clientCache cacheControlMode=\"UseMaxAge\" cacheControlMaxAge=\"0.00:00:30\" />

I've got the following section in my 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>

Here's what I'm trying to do in psuedo-code:

var ext = ".ogg";
var staticContentElements = GetWebConfig().Ge开发者_Python百科tSection("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();

Basically, I need to search the mimeMaps by a fileExtension and get their mimeType.


You need to create a custom configuration section to get that information.


George Stocker's answer led me to a Google search for["staticContent" custom configuration section] which brought me to an iis.net article titled Adding Static Content MIME Mappings <mimeMap>.

The article led me to come up with:

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

Which works perfectly for me. I just need to add some null checks here and there and it should be good to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消