【.net core】读取配置文件Configuration
参考:
https://blog.csdn.net/CsethCRM/article/details/80481020
假设本地json文件如下:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "ConnectionStrings": { "DefaultConnection": "this is a nortal database" }, "AllowedHosts": "*" }
总结起来有两种方式:
1、通过直接读取
//通过Configuration来获取配置项中的内容
var devcon = Configuration.GetConnectionString("DefaultConnection"); //Configuration["ConnectionStrings:DefaultConnection"];
var normal_con = Configuration["ConnectionStrings:DefaultConnection"];
2、稍微复杂一点
a、在StartUp类的ConfigureService添加
services.Configure<Contention>(Configuration.GetSection("ContentionString"));//注册TOption实例对象
b、在Modes里创建节点相同类
public class Contention { public string DefaultConnection{ get; set; } }
c、使用时需要在Controller里读取
private readonly Contention contentions; public ContentController(IOptions<Contention> option) { Contentions= option.Value; }

浙公网安备 33010602011771号