Tôi tạo ra một chức năng để làm điều này mà sẽ sử dụng web.config khu vực nếu người dùng đang sử dụng khu vực khác sẽ sử dụng web.config gốc:
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;
}
Và sau đó gọi:
ForestSettings forestSettings = ConfigFunctions.GetWebConfigSection<ForestSettings>(controller, "myCompanyConfiguration/forestSettings");
tốt, tôi nghĩ rằng nó bất ngờ và bất tiện – Agzam
@Agzam, tôi hoàn toàn đồng ý với bạn nhưng một khi bạn hiểu cách thức hoạt động kế thừa web.config trong ASP.NET (sử dụng thư mục con) và nơi Razor tìm kiếm không gian tên, bạn sẽ thấy rằng nó có ý nghĩa . –
Có liên kết đến tài liệu liên quan đến điều này không? – Mikhail