asp.net core 读取Appsettings.json 配置文件

Appsettingsjson 配置
定义实体
在StartUp时读取配置信息
修改你的Controller通过构造函数进入配置信息
总结
Appsettings.json 配置
很明显这个配置文件就是一个json文件,并且是严格的json文件,所有的属性都需要添加“”引号;
面给出一段自定义的配置文件吧

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"StarInfo": {
"Port": 4567
}
}

定义实体
需要定义一个实体,类型与配置文件匹配,以便将配置文件中的json转成C#中的实体进行操作
实体的代码如下

public class StarInfo
{
public int Port { get; set; }
}

在StartUp时读取配置信息
在startup的ConfigureServices方法中读取配置信息
样例代码:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
//读取配置信息
services.Configure<StarInfo>(this.Configuration.GetSection("StarInfo"));
}

修改你的Controller,通过构造函数进入配置信息
?先说一个疑问:我没有搞清楚这个构造函数的注入是在哪个接口内完成的,等有时间看一下源码吧,否则这种导出都是注入的代码理解起来还是有点困难。

我这里是直接在HomeController中进行修改的,样例代码如下:

public class HomeController : Controller
{
//定义配置信息对象
public StarInfo StarInfoConfig;
//重写构造函数,包含注入的配置信息
public HomeController(IOptions<StarInfo> setting) {
StarInfoConfig = setting.Value;
}
//Action
public IActionResult Index()
{
//读取配置信息,这里也就是使用的地方了
ViewData["Port"] = StarInfoConfig.Port;
return View();
}

posted @ 2019-06-24 11:18  星火卓越  阅读(650)  评论(0编辑  收藏  举报