简体   繁体   English

如何从.Net Core 中的多个 json 文件中读取值?

[英]How to read values from multiple json files in .Net Core?

I want to read values from multiple json files.我想从多个 json 文件中读取值。 Getting the values from default json file but unable to read separately added json file.从默认 json 文件中获取值,但无法读取单独添加的 json 文件。 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.这是 output。 在此处输入图像描述

My Json Files我的 Json 文件

  1. endpoint-defaults.json端点默认值。json

    { {

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

    } }

  2. jsconfig1.js jsconfig1.js

    { {

    "AppSettings": { “应用程序设置”:{

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

    } }

    } }

You can always use multiple json configuration files in building configuration of a .net core application.在构建 .net 核心应用程序的配置时,您始终可以使用多个 json 配置文件。 You can also include XML configuration file.您还可以包含 XML 配置文件。

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.所以这里我将通过一个简单的配置示例和一个asp.net核心应用进行说明。

I have two configuration files.我有两个配置文件。

  1. appsettings.json appsettings.json
  2. apisettings.json 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": "someemail@domain.com",
    "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.然后我创建 C# 类来表示配置部分。

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.现在我将这些 JSON 文件添加到配置生成器中,同时在 Program.cs 文件中构建创建 HostBuilder。

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.上述代码会将 json 配置文件添加到配置生成器并构建配置。

I can now retrieve the configuration sections and translate them to C# classes and use the configuration values.我现在可以检索配置部分并将它们转换为 C# 类并使用配置值。 In following code I am accessing the configuration sections and their values inside ConfigureServices method of Startup class.在下面的代码中,我正在访问Startup class 的ConfigureServices方法中的配置部分及其值。

// 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.您还可以将这些配置部分作为依赖项注入应用程序的其他部分,例如 controller 或服务 class。

For that, you need to add the configuration sections to the service collections so that they get resolved as dependencies.为此,您需要将配置部分添加到服务 collections 以便它们被解析为依赖项。 Change ConfigureService method as following.更改 ConfigureService 方法如下。

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.现在我可以在我的 HomeController 中依赖ProductApi配置部分,如下所示。

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.我希望这能帮助你解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM