.NET Core 读取appsettings.json配置文件
程序员文章站
2023-12-28 14:24:40
...
1、appsettings.json配置文件
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
},
"LogLevel": {
"Default": "Warning"
}
},
"JwtSettings": {
"Issuer": "http://localhost:5200",
"Audience": "http://localhost:5200",
"SecretKey": "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
},
"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;
#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 IOptions<JwtSettings> _setting;
private IConfiguration _configuration;
public HomeController(IOptions<JwtSettings> setting)
{
_setting = setting;
_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;
return View();
}
}
推荐阅读
-
net Core 2.0读取appsettings.json
-
.net core读取配置文件appsettings.json
-
.NET Core读取配置文件appsettings.json
-
.NET Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
Asp .Net Core 读取appsettings.json配置文件
-
asp.net core 读取Appsettings.json 配置文件
-
ASP.NET Core配置教程之读取配置信息
-
ASP.NET Core配置教程之读取配置信息
-
.Net Core库类项目跨项目读取配置文件的方法