【问题标题】:ASP.NET Core appsettings.json need to update on diskASP.NET Core appsettings.json 需要在磁盘上更新
【发布时间】:2018-04-04 01:10:39
【问题描述】:

我目前正在使用 asp.net core v2.0 进行项目,并且在我的 appsettings.json 中有:

"ContextSettings": {
    "ConnectionString": "Data Source={base-path}WahupaWeb.sqlite;Version=3;BinaryGUID=True;datetimeformat=CurrentCulture",
    "Provider": "System.Data.SQLite.EF6",
    "DropCreateDatabaseAlways": "false"
  }

我有一个场景需要更新连接的“数据源” 以编程方式字符串。

我正在阅读并尝试使用此代码更新 JSON 文件。

public class FileController : Controller
{
   private IConfigurationRoot Configuration { get; set; }    
   private void ConfigureConnectionString(string dbFileName)
   {
     var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
                      .SetBasePath(Environment.CurrentDirectory)
                      .AddJsonFile("appsettings.json", false, reloadOnChange: true);
     Configuration = builder.Build();
     Configuration["ContextSettings:ConnectionString"] = sqliteConnectionString;
   }
}

但它没有更新文件名“appsettings.json”。

如何以编程方式更新 appsettings.json 文件。

【问题讨论】:

标签: c# json asp.net-core asp.net-core-2.0 appsettings


【解决方案1】:

配置在技术上是只读的。换句话说,您不能只更改Configuration 对象上的某些内容,然后让它将这些更改写入磁盘。它不是这样设置的。

如果您需要以编程方式更改 appsettings.json 之类的内容,则需要手动读取文件,进行修改并将其写回磁盘。与任何文件一样。由于它是 JSON,因此您可能希望使用 JSON.NET 之类的中介来实际反序列化文件中的 JSON,更改内存中的对象,然后在写入文件之前再次对其进行序列化。

【讨论】:

    猜你喜欢
    • 2014-10-06
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多