ASP.NET Core读取AppSettings.json配置

ASP.NET Core中读取配置字符串,并不像.NET那样直接Configuration.GetConnestionString()简单了,通过Startup.cs查看默认实现,是通过注入的!

在这里插入图片描述

那么我们在其他层又如何去读取呢,通过实际代码发现,是没有GetConnectionString()方法的,也就是说,无法直接通过Configuration进行读取的!

在这里插入图片描述

要想读取,其实也很简单,new 一下ConfigurationBuilder就可以了!

在这里插入图片描述

var config = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json")
                .AddInMemoryCollection()
                .Build();
            var connStr = config["ConnectionStrings:DefaultConnection"];

            DbContextOptions<SysContext> options = new DbContextOptionsBuilder<SysContext>().UseMySQL(connStr).Options;

            SysContext db = new SysContext(options);

可以看到,成功读取,是不是很简单呀!

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42799562/article/details/114301609