.Net Core读取自定义配置文件
比如有个自定义json配置文件:\Settings\Builtin.json
{ "OIDC": { "Host": "http://localhost:8020", "Https": false, "ClientId": "Workspace", "ClientSecret": "bf88b9d30eca4f84be20b7744b2b3573", "Scopes": [ "openid", "profile", "security", "org_profile", "ad_profile", "iam_profile", "access_oaplus" ], "ClaimMaps": [ { "ClaimType": "displayName", "JsonKey": "display_name" }, { "ClaimType": "nickname", "JsonKey": "nickname" } ] } }
Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args, CancellationTokenSource cancellation) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("settings/Builtin.json", false, false);
})
.UseStartup<Startup>();
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.Configure<OpenIdConnectOption>(Configuration.GetSection("OIDC"));
var provider = services.BuildServiceProvider();
var oidcOption = provider.GetRequiredService<IOptions<OpenIdConnectOption>>().Value; }
OpenIdConnectOption 类的结构如下:
public class OpenIdConnectOption
{
public string Host { get; set; }
public bool Https { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string[] Scopes { get; set; }
public ClaimMap[] ClaimMaps { get; set; }
}
public class ClaimMap
{
public string ClaimType { get; set; }
public string JsonKey { get; set; }
}
另外分享一个读取默认配置的工具类
using Microsoft.Extensions.Configuration; using System.IO; namespace EIP.Core.DataAccess { public static class AppsettingsConfig { public static IConfiguration Configuration { get; set; } static AppsettingsConfig() { Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, reloadOnChange: true).Build(); } public static string GetConfigValue(string key) { return Configuration[key]; } } }
使用方法:
var setting = AppsettingsConfig.GetConfigValue("Token:Secret")