[英]How to read a section from web.config on IIS7 w/ .net 4 in C#
我在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>
这是我在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();
基本上,我需要通过fileExtension搜索mimeMaps并获取它们的mimeType。
您需要创建自定义配置部分才能获取该信息。
George Stocker的回答让我在谷歌搜索["staticContent" custom configuration section]
,这使我看到一篇名为添加静态内容MIME映射<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
检查,它应该是好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.