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

I have 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 is what I am trying to do in psuedo code:

 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(); 

Basically, I need to look for mimeMaps using the Extension file and get their mimeType.

+4
source share
2 answers

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

In this article I got:

 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 great for me. I just need to add some null tags here and there, and it should be nice to go.

+1
source

To get this information, you need to create a custom configuration section .

+2
source

Source: https://habr.com/ru/post/1341049/


All Articles