一、
webconfig:在configSections裡建立sectionGroup與section,並依需要設定各環境所需的值
<sectionGroup name="MachineA">
<section name="appSettings" type="System.Configuration.NameValueSectionHandler" />
</sectionGroup>
<MachineA>
<appSettings>
<add key="TestStringA" value="MachineAStrA" />
<add key="TestStringB" value="MachineAStrB" />
</appSettings>
</MachineA>
二、建立ConfigManager類別庫 方便取值
(一)建立ConfigManager類別庫方便做取值使用
(二)建立Service資料夾,新增類別ConfigManagerService.cs
public class ConfigManagerService
{
/// <summary>
/// 取得 AppSettings 介面
/// </summary>
public static readonly NameValueCollection AppSettings = GetConfigurationUsingAppSettings();
private static NameValueCollection GetConfigurationUsingAppSettings()
{
var configName = GetMachineAppSettings();
var postSetting = ConfigurationManager.GetSection(configName) as NameValueCollection;
return postSetting;
}
/// <summary>
/// 取得目前程式運行設備AppSettings
/// </summary>
/// <returns></returns>
private static string GetMachineAppSettings()
{
//預設設備為 MachineA
var defaultMachineName = "MachineA";
var group = "/appSettings";
//取得運行主機名稱
var machineName = Environment.MachineName.Trim().ToUpper();
string machineAName = "MachineA";//設備A名稱
string machineBName = "MachineB";//設備B名稱
if(machineAName.Trim().ToUpper().Contains(machineName))
{
machineName = machineAName;
}
else if (machineBName.Trim().ToUpper().Contains(machineName))
{
machineName = machineBName;
}
else
{
machineName = defaultMachineName;
}
return machineName + group;
}
}
三、需要取appSettings值得專案引用ConfigManager類別庫
四、HomeController:測試是否可成功取值
Controller:
public ActionResult Index()
{
ViewData["TestStringA"] =ConfigManagerService.AppSettings["TestStringA"];
return View();
}
view:
@{
var testStr = ViewData["TestStringA"];
}
<script>
alert('@testStr');
</script>
ps:可切換ConfigManagerService的defaultMachineName A=>B 看值是否有成功從A切換到B環境
留言
張貼留言