学海无涯

导航

使用IOptionsSnapshot读取appsettings配置文件,将Json映射到对象

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-DABHN6U\\MSSQLSERVER2014;uid=sa;pwd=Lz38275292;database=NewAps;MultipleActiveResultSets=true;",
    "RedisConnection": "127.0.0.1:6379"
  },
  "Smtp": {
    "Server": "smtp.youzack.com",
    "UserName": "zack",
    "Password": "hello9999",
    "AllowedHosts": "*"
  }

}

  新添要映射节点 ConnectionStrings、Smtp 对应的类:

 public class SmtpSettings
    {
        public string Server { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
    }

  

 public class DbSettings
    {
        public string DefaultConnection { get; set; }
        public string RedisConnection { get; set; }
    }

  注册服务:

//注入配置服务到容器,以便读取appsetting.json
builder.Services.AddOptions()
    .Configure<DbSettings>(m => builder.Configuration.GetSection("ConnectionStrings").Bind(m))
    .Configure<SmtpSettings>(m => builder.Configuration.GetSection("Smtp").Bind(m));

  读取:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Net.WebSockets;
using TestWebApplication.Configuration;

namespace TestWebApplication.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ReadConfigUseOptionsController : ControllerBase
    {
        private readonly IOptionsSnapshot<DbSettings> optDbSetting;
        private readonly IOptionsSnapshot<SmtpSettings> optSmtpSetting;
        private readonly ILogger logger;
        public ReadConfigUseOptionsController(ILogger<ReadConfigUseOptionsController> logger, IOptionsSnapshot<DbSettings> optDbSetting, IOptionsSnapshot<SmtpSettings> optSmtpSetting)
        {
            this.logger = logger;
            this.optDbSetting = optDbSetting;
            this.optSmtpSetting = optSmtpSetting;
        }

        [HttpGet("ReadDbSettings")]
        public async Task<ActionResult<DbSettings>> ReadDbSettings()
        {
            var db = optDbSetting.Value;
            return Ok(db);
        }
        [HttpGet("ReadSmtpSettings")]
        public async Task<ActionResult<SmtpSettings>> ReadSmtpSettings()
        {
            var db = optSmtpSetting.Value;
            return Ok(db);
        }

    }


}

  注意:

IOptions<> 类型有三种方式:

1. IOptions<T>  配置更改后,必须重启程序才能获取新值。

2. IOptionsMonitor<T> 配置更改后,立即读取新值。

3. IOptionsSnapshot<T> 配置更改后,立即读取新值,但在同范围里会保持一致性。

读取后不需要更改:使用IOptions<T>  ,否则使用IOptionsSnapshot<T>

 

posted on 2022-09-25 18:52  宁静致远.  阅读(102)  评论(0编辑  收藏  举报