我想在NET Core 2.2的运行时更改放置在appsettings.json文件中的连接字符串。
所以我的工作是:
我认为步骤1.可以,我使用此代码,appsettings.json成功更改:
public static void ChangeConnectionStringsInAppSettings(eConnectionStringType cstrType, string value)
{
var d = AppDomain.CurrentDomain.BaseDirectory;
ChangeSettingsFile(Path.Combine(d, "appsettings.json"), cstrType, value);
ChangeSettingsFile(Path.Combine(d, "appsettings.Development.json"), cstrType, value);
ChangeSettingsFile(Path.Combine(d, "appsettings.Production.json"), cstrType, value);
}
private static void ChangeSettingsFile(string appSettingsJsonFilePath, eConnectionStringType cstrType, string value)
{
if (System.IO.File.Exists(appSettingsJsonFilePath))
{
var json = System.IO.File.ReadAllText(appSettingsJsonFilePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(json);
if (cstrType == eConnectionStringType.Identity)
{
jsonObj["ConnectionStrings"]["IdentityConnection"] = value;
}
else if (cstrType == eConnectionStringType.Data)
{
jsonObj["ConnectionStrings"]["DefaultConnection"] = value;
}
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
System.IO.File.WriteAllText(appSettingsJsonFilePath, output);
}
}
使用setp 2和3,我遇到了问题。我尝试使用DI使IOptionsMonitor工作,但它始终显示旧值:
public class Startup
{
public class ConnectionStrings
{
public string IdentityConnection { get; set; }
}
public void ConfigureServices(IServiceCollection services)
// ...
services.Configure<ConnectionStrings>(Configuration.GetSection("ConnectionStrings"));
// ...
}
}
控制器:
public RolesController(
AuthContext ACTX
, MySiteContext CTX
, UserManager<ApplicationUser> userManager
, RoleManager<ApplicationRole> roleManager
, IConfiguration configuration
, IStringLocalizer localizer
, My my
, IRolesRepository repo
, IOptionsMonitor<ConnectionStrings> options)
: base(ACTX, CTX, userManager, roleManager, configuration, localizer, my, repo)
{
var _myValues = options.CurrentValue;
}
[UseAjax]
[UseTelerik]
[UseClientSideValidation]
public IActionResult Index()
{
ChangeConnectionStringsInAppSettings(eConnectionStringType.Identity, "old");
this.CheckDatabase();
return View(new ApplicationRoleDto());
}
[UseAjax]
[UseTelerik]
[UseClientSideValidation]
public IActionResult Index2()
{
ChangeConnectionStringsInAppSettings(eConnectionStringType.Identity, "new");
this.CheckDatabase();
return View("Index",new ApplicationRoleDto());
}
我要停在这一步。新值未加载,成功后,我需要为所有datacontext设置新的connetiontion字符串。
能帮我吗?谢谢!