How can I add a Json string in a launchsettings.json file in my app and read the values?

259 views Asked by At

I have a react front end and c# backend app. I have a launchsettings.json file where i put some configuration. I want to add a string and read that in my c# app

I have tried adding something like the following in my launchsettings.json file:

"jsondata": 
{
 "value1": "value1data",
 "value2": "value2data", 
 "value3": "value3data"
}

So in my C# code I have a value let's say value2, I want to be able to get the Json data and then filter out "value2" and then extract "value2data" to use in my app.

How can I do this in C#?

2

There are 2 answers

3
Suresh Chikkam On BEST ANSWER

I have added Json string in the launchsettings.json file and able to read the values.

  • Here, I have taken C# web application and added Json string.

Program.cs:

namespace WebApplication2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddRazorPages();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            // Read the jsondata environment variable
            var jsonData = Environment.GetEnvironmentVariable("jsondata");

            if (!string.IsNullOrEmpty(jsonData))
            {
                var json = JObject.Parse(jsonData);
                var value1 = json["value1"]?.ToString();

                // Pass value1 to the Razor Page
                app.Use(async (context, next) =>
                {
                    context.Items["Value1"] = value1;
                    await next();
                });
            }
            app.MapRazorPages();

            app.Run();
        }
    }
}

Here is my launchsettings.json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:54494",
      "sslPort": 44352
    }
  },
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "jsondata": "{\"value1\": \"294729729\", \"value2\": \"439849475\", \"value3\": \"84593846\"}"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7181;http://localhost:5001",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "jsondata": "{\"value1\": \"294729729\", \"value2\": \"439849475\", \"value3\": \"84593846\"}"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "jsondata": "{\"value1\": \"value1data\", \"value2\": \"value2data\", \"value3\": \"value3data\"}"
      }
    }
  }
}
  • By using var jsonData = Environment.GetEnvironmentVariable("jsondata"); able to get the values which is under EnvironmentVariable inside the launchsettings,json.

enter image description here

1
Selaka Nanayakkara On

Given you launchSettings.json file looks like this :

{
  "profiles": {
    "YourAppName": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;https://localhost:5000",
      "environmentVariables": {
        "CustomSettings": "{\"key1\": \"value1\", \"key2\": \"value2\"}" //add params as you wish here
      }
    }
  }
}

In your program.cs file you can access it via the IConfiguration below :

using Microsoft.Extensions.Configuration;

    class Program
    {
        static void Main(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json") // You may need to adjust the file path
                .Build();
    
            string customSettingsJson = config["CustomSettings"];
          
            dynamic customSettings = Newtonsoft.Json.JsonConvert.DeserializeObject(customSettingsJson);
    
            
            string key1Value = customSettings.key1; // Access individual values
            string key2Value = customSettings.key2; // Access individual values
    
            
            Console.WriteLine($"Key1: {key1Value}, Key2: {key2Value}");
        }
    }