Search code examples
c#jsonasp.net-core.net-coreblazor-server-side

How to set app settings value programmatically in Blazor server-side


I need to pass UserId as part of Serilog logging. For this I created a new variable UserId with empty value in app settings, and set the value programmatically in index.razor.

This code shown here is not working. How do I set the value for userId in appsettings.json?

Appsettings.json:

"Serilog": {
   "Using": [],
   "MinimumLevel": {
     "Default": "Information",
     "Override": {
       "Microsoft": "Warning",
       "System": "Warning"
     }
   },
   "WriteTo": [
     {
       "Name": "Seq",
       "Args": { "serverUrl": "https://logging.mysite.com" }
     }
   ],   
   "Properties": {
     "ApplicationName": "TESTApp",
     "Environment": "DEV"
     "UserId": ""
   }
}

index.razor:

protected override async Task OnInitializedAsync()
{     
     UserName = GetUserId();
     Configuration["Serilog:Properties:UserId"] = UserName;     
}

Solution

  • I think you want changing the json file. You could try use "JsonObject" for easily modify the json text.

    @using System.Text.Json
    @using System.Text.Json.Nodes
    
            var filePath = "appsettings.json";
            var oldjson = File.ReadAllText(filePath);
            var jsonobject = JsonObject.Parse(oldjson);
            jsonobject["Serilog"]["Properties"]["UserId"] = UserName;
            var newjson = jsonobject.ToString();
            File.WriteAllText(filePath, newjson);
    

    After the file has changed , builder.Configuration will change automatically. Or you could make sure the configuration is reloaded when file change.

    builder.Configuration.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);