环境变量配置提供程序  
文件配置提供程序  
XML 配置提供程序  
ASP.NET Core 中的静态文件  
在 ASP.NET Core 中使用多个环境  Development、Staging、Production

IConfiguration 接口
命名空间:Microsoft.Extensions.Configuration
程序集:Microsoft.Extensions.Configuration.Abstractions.dll

ConfigureServices 方法  
Namespace:Microsoft.AspNetCore.Hosting
Assembly:Microsoft.AspNetCore.Hosting.dll

IServiceCollection
对于需要大量设置的功能,IServiceCollection 上有 Add{Service} 扩展方法。 例如,AddDbContext、AddDefaultIdentity、AddEntityFrameworkStores 和 AddRazorPages:
命名空间:Microsoft.Extensions.DependencyInjection
程序集:Microsoft.Extensions.DependencyInjection.Abstractions.dll

1、appsettings.json配置文件

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=CoreDb;User ID=sa;Password=000000",
    "SqlConnection": "Server=.;Database=CoreDb;User ID=sa;Password=123456",
    "DevConnection": "Server=.;Database=CoreDb;User ID=sa;Password=1qaz",
    "MYSQLCONNSTR_": "",
    "SQLCONNSTR_": "",
    "SQLAZURECONNSTR_": "",
  },
  "AppSetting": {
    "AdminSafeList": "127.0.0.1;192.168.1.5;::1", //IP 安全列表
    "Cores": "https://localhost:44390,http://0.0.0.0:3201", //跨域
    "UploadFilesRootPath": "E:\\uploadfiles"
  },
  "Appsettings": {
    "SystemName": "Test .NET CORE",
    "Date": "2019-01-01",
    "Author": "Test"
  },
  "RedisOptions": {
    "Host": "127.0.0.1",
    "Prot": "1234"
  },
  "RabbitMQOptions": {},
  "ConsulOptions": {},
  "Authentication": {
    "WeChat": {
      "AppId": "微信AppID",
      "AppSecret": "微信AppSecret"
    }
  },
  "Weixin": {
    "AppId": "wxd9bae9d99a99f9ec"
  },
  "SMS": {
    "Url": "https://sms.yunpian.com/v1/sms/send.json"
  },
  "Service": {
    "Name": "clientservice",
    "Port": "5010",
    "DocName": "clientservice",
    "Version": "v1",
    "Title": "CAS Client Service API",
    "Description": "CAS Client Service API provide some API to help you get client information from CAS",
    "Contact": {
      "Name": "CAS 2.0 Team",
      "Email": "EdisonZhou@manulife.com"
    },
    "XmlFile": "Manulife.DNC.MSAD.IdentityServer4Test.ApiService01.xml"
  },
  "Identity": {
    "IP": "localhost",
    "Port": "5000",
    "Scheme": "Bearer"
  },
  "JwtSettings": {
    "Issuer": "http://localhost:5200",
    "Audience": "http://localhost:5200",
    "SecretKey": "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
  },
  "Certificates": {
    "CerPath": "certificate\\cas.clientservice.pfx",
    "Password": "manulife"
  },
  "TestName": "123456789",
  "AllowedHosts": "*"
}

2、Startup.cs文件

public void ConfigureServices(IServiceCollection services)
{
    string audience = string.Empty;
    string issuer = string.Empty;
    string secretKey = string.Empty;

    #region 从appsettings.json文件中读取JwtSettings相关配置信息

    services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
    JwtSettings setting = new JwtSettings();
    Configuration.Bind("JwtSettings", setting);

    audience = setting.Audience;
    issuer = setting.Issuer;
    secretKey = setting.SecretKey;

    string appId = Configuration["Authentication:WeChat:AppId"];
    string appSecret = Configuration["Authentication:WeChat:AppSecret"];

    #endregion

    services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

3、JwtSettings.cs文件

public class JwtSettings
{
    /// <summary>
    /// 证书颁发者
    /// </summary>
    public string Issuer { get; set; }

    /// <summary>
    /// 允许使用的角色
    /// </summary>
    public string Audience { get; set; }

    /// <summary>
    /// 加密字符串
    /// </summary>
    public string SecretKey { get; set; }
}

4、Controller 

using Microsoft.Extensions.Options;
using Microsoft.Extensions.Configuration;

public class HomeController : Controller
{
    private readonly IOptions<JwtSettings> _setting;
    private readonly JwtSettings _settingOptions;

    private readonly IConfiguration _configuration;

    public HomeController(IOptions<JwtSettings> setting)
    {
        _setting = setting;
        _settingOptions= setting.Value;
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        JwtSettings setting = new JwtSettings();
        _configuration.Bind("JwtSettings", setting);

        string secretKey = _setting.Value.SecretKey;
        string issuer = _setting.Value.Issuer;
        string audience = _setting.Value.Audience;

        string secretKey = _settingOptions.SecretKey;
        string issuer = _settingOptions.Issuer;
        string audience = _settingOptions.Audience;

        return View();
    }
}

=========【.NET Core 类库 读取 .json 文件】=========

【注意:appsettings.json 右键属性 -> 将“复制到输出目录”值改为“始终复制”】

【注意:appsettings.json 右键属性 -> 将“复制到输出目录”值改为“始终复制”】

【注意:appsettings.json 右键属性 -> 将“复制到输出目录”值改为“始终复制”】

1、创建一个 .NET Core 类库(Test.CoreLibrary),新建 ConfigManager.cs 类

管理 NuGet 程序包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace Test.CoreLibrary
{
    /// <summary>
    /// 读取配置文件
    /// NuGet: Install-Package Microsoft.Extensions.Configuration
    /// NuGet: Install-Package Microsoft.Extensions.Configuration.Abstractions
    /// NuGet: Install-Package Microsoft.Extensions.Configuration.Json
    /// </summary>
    public class ConfigManager
    {
        public static IConfiguration Configuration { get; set; }

        static ConfigManager()
        {
            //ReloadOnChange = true 当appsettings.json被修改时重新加载            

            #region 方式1(ok)
            Configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource
                {
                    Path = "appsettings.json",
                    ReloadOnChange = true
                }).Build();
            #endregion

            #region 方式2(ok)
            //Configuration = new ConfigurationBuilder()
            //    .SetBasePath(Directory.GetCurrentDirectory())
            //    .AddJsonFile("appsettings.json").Build();
            #endregion

            #region 方式3读取过个配置文件(ok)
            Configuration = configuration;

            var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
               .AddJsonFile("configuration.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables();
            Configuration = builder.Build();
            #endregion
        }
    }
}

=========【Program.cs 添加json文件】=========

using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace WebAPI
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(conf =>
            {
                conf.AddJsonFile("configurations.json", false, true);
            })
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    }
}

2、在controller中使用 ConfigManager 类,读取 appsettings.json 配置文件  

using System;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Test.CoreLibrary;

namespace Web.Test1.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            //获取应用程序根目录
            var configBasePath = Directory.GetCurrentDirectory();

            //获取bin目录路径
            var baseDirectory = AppContext.BaseDirectory;

            var conn = ConfigManager.Configuration.GetConnectionString("DefaultConnection");
            var sqlConn = ConfigManager.Configuration.GetConnectionString("SqlConnection");
            var devConn = ConfigManager.Configuration.GetConnectionString("DevConnection");

            //读取一级配置节点配置
            var name = ConfigManager.Configuration["TestName"];
            //读取二级子节点配置
            var a = ConfigManager.Configuration["Appsettings:SystemName"];
            var b = ConfigManager.Configuration["Appsettings:Author"];

            var name1 = ConfigManager.Configuration.GetSection("TestName").Value;
            var a1 = ConfigManager.Configuration.GetSection("Appsettings:SystemName").Value;
            var b1 = ConfigManager.Configuration.GetSection("Appsettings:Author").Value;

            return View();
        }
    }
}

========= 在Controller中直接依赖注入IConfiguration =========

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Project.Controllers
{
    [Route("[controller]/[action]")]
    public class WeatherForecastController : Controller
    {
        private IConfiguration _configuration;

        public WeatherForecastController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public IActionResult Index()
        {
            var connection = _configuration["ConnectionStrings:DefaultConnection"];
            return Ok();
        }
    }
}

读取appsetting.json文件

static IConfigurationRoot config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
config["AccessKey"];
config["SecretKey"];
config["Host"];

========= 读取appsettings.json中文乱码 =========
【工具】【自定义】【命令】【添加命令】【文件】【高级保存选择(V)...】【关闭】
打开【appsettings.json】文件,选择【高级保存选择(V)...】【编码】【Unicode (UTF-8 带签名) - 代码页 65001】

========= .NET Framework读取App.config文件配置信息 =========

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<connectionStrings>
		<add name="SqlConnection" connectionString="Data Source=.;Initial Catalog=db;User ID=sa;Password=000000;" providerName="System.Data.SqlClient" />
	</connectionStrings>
	<appSettings>
		<add key="Code" value="123456"/>
	</appSettings>
</configuration>

*

public readonly string dbConnectionStr = ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString;
public readonly string sql = ConfigurationManager.AppSettings["Code"];

*
*
*

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
960b763e 3 个月前
8c391e04 6 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐