我創建了一個函數來做到這裏面,如果用戶使用的區域,否則將使用根web.config將使用面積的web.config:
public static T GetWebConfigSection<T>(Controller controller, string sectionName) where T : class
{
T returnValue = null;
String area = null;
var routeArea = controller.RouteData.DataTokens["area"];
if(routeArea != null)
area = routeArea.ToString();
System.Configuration.Configuration configFile = null;
if (area == null)
{
// User is not in an area so must be at the root of the site so open web.config
configFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");
}
else
{
// User is in an Area, so open the web.config file in the Area/views folder (e.g. root level for the area)
configFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Areas/" + area + "/Views");
}
if (configFile != null)
returnValue = configFile.GetSection(sectionName) as T;
return returnValue;
}
然後調用:
ForestSettings forestSettings = ConfigFunctions.GetWebConfigSection<ForestSettings>(controller, "myCompanyConfiguration/forestSettings");
來源
2012-02-27 11:07:19
Jon
很好,我認爲這是意想不到的不便 – Agzam 2011-05-09 20:09:50
@Agzam,我絕對同意你的觀點,但一旦你理解的web.config繼承在ASP.NET如何工作(使用子文件夾),並在剃刀查找命名空間,你會看到,它是有道理的。 – 2011-05-09 20:10:59
有沒有關於此文檔的鏈接? – Mikhail 2012-10-23 08:05:02