ASP.NET Core appsettings.json update in code

后端 未结 9 1988
小鲜肉
小鲜肉 2020-12-13 01:54

I am currently working on project using asp.net core v1.1, and in my appsettings.json I have:

\"AppSettings\": {
   \"AzureConnectionKey\": \"***\",
   \"Azu         


        
9条回答
  •  离开以前
    2020-12-13 02:22

    There is an esier answer to modify the appsettings.json at runtime.

    Json File structure

    var filePath = Path.Combine(System.AppContext.BaseDirectory, "appSettings.json");
    
    string jsonString = System.IO.File.ReadAllText(filePath);
    
    //use https://json2csharp.com/ to create the c# classes from your json
    Root root = JsonSerializer.Deserialize(jsonString);
    
    var dbtoadd = new Databas()
    {
        Id = "myid",
        Name = "mynewdb",
        ConnectionString = ""
    };
    
    //add or change anything to this object like you do on any list
    root.DatabaseSettings.Databases.Add(dbtoadd);
    
    //serialize the new updated object to a string
    string towrite = JsonSerializer.Serialize(root);
    
    //overwrite the file and it wil contain the new data
    System.IO.File.WriteAllText(filePath, towrite);
    

提交回复
热议问题