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#?
I have added Json string in the launchsettings.json file and able to read the values.
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\"}"
}
}
}
}
var jsonData = Environment.GetEnvironmentVariable("jsondata");
able to get the values which is under EnvironmentVariable inside the launchsettings,json.