关于DotnetCore 配置文件读取IOptionsSnapshot的使用小结

关于dotnetCore里丰富多样的配置方法我就不多说了,不太了解的推荐看下A大的博客系列(https://www.cnblogs.com/artech/p/inside-asp-net-core-05-01.html)

这次主要讲讲项目遇到的需求, 在网站启动的时候从配置文件里读取工作模式(边缘计算或云端计算), 然后运行中途可以通过请求切换。 咋一看其实使用Redis去缓存和修改这个信息是极好的,但要是我还想在外部手动修改配置文件来使它生效的话,redis我就不能通知到了(其实是可以的,在ConfigurationBuilder.GetReloadToken() 注册一个配置文件变化的回调函数,见https://www.debugger.wiki/article/html/1597886280245738 ). 所以我查到了这个方法IOptionsSnapshot,介绍得比较少,官网文档上说支持1.1以上。

首先是要感谢两篇博文的启发 Auto Refresh Settings Changes in ASP.NET Core Runtime 和.net core 读取、修改配置文件appsettings.json

由于需要中途切换,需要能改动到配置文件,然后能马上起作用,平常用的IOptions注入是不会有变化的,而Core就推出了这个IOptionsSnapshot,它是scope的生命周期,每次注入都是新的对象(由此可知IOptions是singleton的生命周期)

然后我就把这需要额外变动的配置信息写到一个 exconfig.json里

{"ExConfigOption":{"serverMode":1}}

在Startup.cs做修改

public Startup(IConfiguration configuration)
{
       _conf = new ConfigurationBuilder()
                .AddConfiguration(configuration) //原有的appsetting.json的配置信息
                .AddJsonFile("exconfig.json", optional: false, reloadOnChange: true) //额外增加的exconfig.json信息
                .Build();
}

public void ConfigureServices(IServiceCollection services)
{
       services.Configure<ExConfigOption>(_conf.GetSection("ExConfigOption").Bind); 
}

在Controller里只需要注入IOptionsSnapshot即可读取最新的信息。然后请求修改的时候则对配置文件直接修改

 public class SystemController : ControllerBase
    {

        private readonly ExConfigOption _exOption;

        public SystemController(IOptionsSnapshot<ExConfigOption> option)
        {
            _exOption = option.Value;
        }

        [HttpGet("GetServerMode")]
        public JsonResult GetServerMode([FromQuery]ApiRequestBody request)
        {
            ReturnResult rst = new ReturnResult();
            rst.data= new {serverMode=_exOption.serverMode };
            return new JsonResult(rst);
        }

        [HttpPost("ChangeServerMode")]
        public JsonResult ChangeServerMode([FromBody] ApiRequestBody request)
        {
            ReturnResult rst = new ReturnResult();
            var filePath = Path.Combine(AppContext.BaseDirectory,"aiconfig.json");
            JObject jsonObject;
            using (StreamReader file = new StreamReader(filePath))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                jsonObject = (JObject)JToken.ReadFrom(reader);
                jsonObject["ExConfigOption"]["serverMode"] = request.serverMode;
            }
            using (var writer = new StreamWriter(filePath))
            using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
            {
                jsonObject.WriteTo(jsonwriter);
            }
            return new JsonResult(rst);
        }
    }
}

 

单元测试使用Mock的时候:

var options = new ExConfigOption(){serverMode = 1 };
var mockOp = new Mock<IOptionsSnapshot<ExConfigOption>>();
mockOp.Setup(m => m.Value).Returns(options);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值