.Net Core中读取json配置文件

1、编写实例化类。新建可供实例化的配置类JwtConfig

/// <summary>
/// Jwt的配置类
/// </summary>
public class JwtConfig
{
    /// <summary>
    /// 定位
    /// </summary>
    public const string Position = "Jwt";

    /// <summary>
    /// 验证签发人
    /// </summary>

    public bool ValidateIssuer { get; set; } = true;

    /// <summary>
    /// 验证有效期
    /// </summary>
    public bool ValidateLifetime { get; set; } = true;
    /// <summary>
    /// 验证签名
    /// </summary>

    public bool ValidateIssuerSigningKey { get; set; } = true;

    
    /// <summary>
    /// 必须包含过期时间
    /// </summary>
    public bool RequireExpirationTime { get; set; } = true;

    /// <summary>
    /// 签发人
    /// </summary>
    public string Issuer { get; set; } = string.Empty;
    /// <summary>
    /// 签名key
    /// </summary>
    public string SecretKey { get; set; } = string.Empty;
    /// <summary>
    /// 偏移时间。秒
    /// </summary>
    public int ClockSkew { get; set; } = 0;
}

2、添加配置文件。在项目根目录添加配置文件jwt.jso,在文件属性中选择“如果较新则复制”

{
  "Jwt": {
    "ValidateIssuer": true,
    "ValidateLifetime": true,
    "ValidateIssuerSigningKey": true,
    "RequireExpirationTime": true,
    "Issuer": "Ninesky",
    "SecretKey": "VA_aLFng0lBp0@DN@@S3vMJ@xU2XN1je",
    "ClockSkew": 30
  }
}

3、读取配置文件,并添加到配置中

打开项目的Program.cs文件

在var builder = WebApplication.CreateBuilder(args);之后,var app = builder.Build();之前添加

builder.Configuration.AddJsonFile("jwt.json", false, true);

4、将配置注入到容器中。

在上一语句后添加代码

builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection(JwtConfig.Position));

整个看起来如下:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);


// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Configuration.AddJsonFile("jwt.json", false, true);
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection(JwtConfig.Position));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

5、在Program.cs中使用配置

在第4部的后面添加代码

var jwtConfig = builder.Configuration.GetSection(JwtConfig.Position).Get<JwtConfig>();

然后直接使用实例化类jwtConfig

6、在控制器中使用

在控制器的构造函数中注入IOptionsSnapshot<JwtConfig>

 [Route("[controller]")]
 [ApiController]
 public class TokenController : ControllerBase
 {
     private JwtConfig jwtConfig;
     public TokenController(IOptionsSnapshot<JwtConfig> options) {
     
         this.jwtConfig = options.Value;
     }
 }
posted @ 2023-10-30 15:21  洞庭夕照  阅读(285)  评论(0编辑  收藏  举报