Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

c# - How to read values from multiple json files in .Net Core?

I want to read values from multiple json files. Getting the values from default json file but unable to read separately added json file. below is my code.

 //Reads from endpoint-defaults.json
        var endpointDefaultsBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                     .AddJsonFile("endpoint-defaults.json", true, true)                         
                     .AddEnvironmentVariables();
        ConfigurationEndpointDefaults = endpointDefaultsBuilder.Build();
        string signOnType = ConfigurationEndpointDefaults.GetSection("AppSettings:mastercard.mip.signOnType").Value;
       var mscdGamingList = ConfigurationEndpointDefaults.GetSection("AppSettings:paymentPostCountryProhibitionCheckStage.mscdGamingList.list").Get<string[]>();


        //Reads from config.json
        var configbuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("jsconfig1.json", true, true)
                .AddEnvironmentVariables();
        Configuration = configbuilder.Build();
        string environmentMode = Configuration.GetSection("AppSettings:mastercard.mip.hostname").Value;

Here is the output. enter image description here

My Json Files

  1. endpoint-defaults.json

    {

       "AppSettings": {
    
         //Default MasterCard properties
         "mastercard.mip.signOnType": "ONDEMAND",
         "mastercard.mip.responseTimeout": 30,    
     }
    

    }

  2. jsconfig1.js

    {

    "AppSettings": {

     "mastercard.mip.hostname": "localhost",
     "mastercard.mip.authorisation_port": 19092,
     "mastercard.mip.test_authorisation_port": 19094,
    

    }

    }

question from:https://stackoverflow.com/questions/65546723/how-to-read-values-from-multiple-json-files-in-net-core

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can always use multiple json configuration files in building configuration of a .net core application. You can also include XML configuration file.

I have very little to no knowledge about the the configuration structure and the values you are using. So here I will explain with a simple configuration examples and a asp.net core application.

I have two configuration files.

  1. appsettings.json
  2. apisettings.json

Both the above configuration files have multiple configuration sections in them.

//appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "DbSettings": {
    "ConnectionString": "Data Source=localhost; Initial Catalog=CareCMSDatabase;User ID=sa; Password=Password1; TimeOut=30;"
  },
  "SmtpSettings": {
    "UserName": "[email protected]",
    "Host": "someserver.smtp.com",
    "Port": "587",
    "Password":  "password"
  }
}

//apisettings.json
{
  "ProductApi": {
    "BaseUrl": "https://www.products.com/",
    "AuthEndpoint": "api/2.0/Auth/",
    "ClientId": "somelcientid",
    "ClientSecret": "someclientsecret"
  },
  "SearchApi": {
    "BaseUrl": "https://www.search.com/",
    "RandomEndpoint": "api/random",
    "AuthToken":  "sometoken"
  }
}

Then I create C# classes to represent the configuration sections.

public class SmtpSettings
{
    public string Host { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public int Port { get; set; }
}

public class DbSettings
{
    public string ConnectionString { get; set; }
}

public class ProductApiSettings
{
    public string BaseUrl { get; set; }
    public string AuthEndpoint { get; set; }
    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
}

public class SearchApiSettings
{
    public string BaseUrl { get; set; }
    public string RandomEndpoint { get; set; }
    public string AuthToken { get; set; }
}

Now I add these JSON files to the configuration builder while building Creating HostBuilder in Program.cs file.

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.ConfigureAppConfiguration((builder) => {
                    builder.SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .AddJsonFile("apisettings.json")
                    .AddEnvironmentVariables();
                });
                webBuilder.UseStartup<Startup>();
            });

The above code will add the json configuration files to the configuration builder and build the configuration.

I can now retrieve the configuration sections and translate them to C# classes and use the configuration values. In following code I am accessing the configuration sections and their values inside ConfigureServices method of Startup class.

// This method gets called by the runtime. Use this method to add services to the container.

    public void ConfigureServices(IServiceCollection services)
    {
        // Get DbSettings section from the configuration file.
        var dbSettingSection = Configuration.GetSection("DbSettings");

        // Get Configuration value and convert it to C# class object.
        var dbSettings = dbSettingSection.Get<DbSettings>();
        // Now I can access ConnectionString value from the configuration by accessing dbSettings.ConnectionString

        //Same as above, get ProductApi Section from the configuration file.
        var productApiSection = Configuration.GetSection("ProductApi");

        // Get the configuartion value and convert it to C# class object.
        var productApiSettings = productApiSection.Get<ProductApiSettings>();

        var smtpSection = Configuration.GetSection("SmtpSettings");

        var smtpSettings = smtpSection.Get<SmtpSettings>();

        var searchApiSection = Configuration.GetSection("SearchApi");

        var searchApiSettings = searchApiSection.Get<SearchApiSettings>();

        var authToken = Configuration["SearchApi:AuthToken"];

        services.AddControllersWithViews();
    }

You can also inject these configuration sections as dependencies in other parts of the application such as controller or service class.

For that, you need to add the configuration sections to the service collections so that they get resolved as dependencies. Change ConfigureService method as following.

public void ConfigureServices(IServiceCollection services)
    {
        var dbSettingSection = Configuration.GetSection("DbSettings");

        // Add the section to service collection.
        services.Configure<DbSettings>(dbSettingSection);

        var productApiSection = Configuration.GetSection("ProductApi");

        services.Configure<ProductApiSettings>(productApiSection);

        var smtpSection = Configuration.GetSection("SmtpSettings");

        services.Configure<SmtpSettings>(smtpSection);

        var searchApiSection = Configuration.GetSection("SearchApi");

        services.Configure<SearchApiSettings>(searchApiSection);

        services.AddControllersWithViews();
    }

Now I can have dependency on, let say ProductApi config section, in my HomeController as following.

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    // Field for ProductApiSettings
    private ProductApiSettings _productApiSettings;

    public HomeController(IOptions<ProductApiSettings> productsApiSettings, Logger<HomeController> logger)
    {
        _logger = logger;
        // Initilizing settings object from the dependency.
        // This will have the values retrieved from the json config files.
        _productApiSettings = productsApiSettings.Value;
    }

    public IActionResult Index()
    {
        // Using properties from the settings
        var productApiAuthURL = _productApiSettings.BaseUrl + _productApiSettings.AuthEndpoint;

        return View();
    }
}

I hope this will help you solve your issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...