本文介绍了如何从 .Net Core 中的多个 json 文件中读取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从多个 json 文件中读取值.从默认 json 文件中获取值,但无法读取单独添加的 json 文件.下面是我的代码.

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;

这是输出.

我的 Json 文件

  1. endpoint-defaults.json

  1. endpoint-defaults.json

{

   "AppSettings": {

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

}

jsconfig1.js

jsconfig1.js

{

应用设置":{

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

}

}

推荐答案

在构建 .net 核心应用程序的配置时,您始终可以使用多个 json 配置文件.您还可以包含 XML 配置文件.

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

我对您使用的配置结构和值知之甚少或一无所知.所以这里我会用一个简单的配置例子和一个asp.net核心应用来解释.

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.

我有两个配置文件.

  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"
  }
}

然后我创建 C# 类来表示配置部分.

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; }
}

现在我将这些 JSON 文件添加到配置生成器,同时在 Program.cs 文件中构建创建 HostBuilder.

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>();
            });

以上代码会将json配置文件添加到配置构建器中,并构建配置.

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

我现在可以检索配置部分并将它们转换为 C# 类并使用配置值.在以下代码中,我访问了 Startup 类的 ConfigureServices 方法中的配置部分及其值.

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.

为此,您需要将配置部分添加到服务集合中,以便将它们解析为依赖项.更改 ConfigureService 方法如下.

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();
    }

现在我可以依赖 HomeController 中的 ProductApi 配置部分,如下所示.

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.

这篇关于如何从 .Net Core 中的多个 json 文件中读取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:56