does mvc support inheritance of Web.config settings throughout areas?
I distributed my MVC code into a few different areas and noticed one thing. if I have something in the main Web.config, something like:
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Collections.Generic" />
those pages that don't belong to the root area know nothing about that. And I have to repeat the same thing in the inner Web.config, th开发者_JAVA百科e one that sits in the area folder.
How come?
web.config
inherit but only to subfolders. ~/Areas
is a separate folder from ~/Views
so what you put in ~/Areas/SomeAreaName/Views/web.config
has nothing in common with what you put in ~/Views/web.config
. And because Razor ignores the namespaces section in ~/web.config
you kinda need to repeat it for areas.
In summary you have:
~/Views/web.config
~/Areas/SomeAreaName/Views/web.config
which are two completely distinct folders and sections in them cannot be inherited.
I created a function to do this which will use the area web.config if the user is using the area otherwise will use the root 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;
}
And then call:
ForestSettings forestSettings = ConfigFunctions.GetWebConfigSection<ForestSettings>(controller, "myCompanyConfiguration/forestSettings");
精彩评论