欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

 

上一篇:

下一篇: