asp.net core 读取appsettings.json配置项
2018-01-18 15:34
821 查看
1.新建一个asp.net core 项目
2.打开appsettings.json,加入配置项
3.创建相应的Model
Job.cs
JobItem.cs
StarInfo.cs
4.在Startup.cs中加入获取项
5.注入到Controller中
6.输出结果
点击下载代码
2.打开appsettings.json,加入配置项
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "StarInfo": { //普通方式 "Port": 3362 }, "Job": { "Name": "王小二" }, "JobList": [ //集合方式 { "Name": "王小二", "Age": 29, "sex": "男" }, { "Name": "李一一", "Age": 22, "sex": "女" } ] }
3.创建相应的Model
Job.cs
public class Job { public string Name { get; set; } }
JobItem.cs
public class JobItem { public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } }
StarInfo.cs
public class StarInfo { public int Port { get; set; } }
4.在Startup.cs中加入获取项
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //读取配置信息 services.Configure<StarInfo>(this.Configuration.GetSection("StarInfo")); //读取配置信息 services.Configure<Job>(this.Configuration.GetSection("Job")); services.Configure<List<JobItem>>(this.Configuration.GetSection("JobList")); }
5.注入到Controller中
public class HomeController : Controller { public StarInfo StarInfoConfig; public Job JobConfig; public List<JobItem> JobListConfig; //重写构造函数,包含注入的配置信息 public HomeController(IOptions<StarInfo> setting, IOptions<Job> jobsetting, IOptions<List<JobItem>> joblistsetting) { StarInfoConfig = setting.Value; JobConfig = jobsetting.Value; JobListConfig = joblistsetting.Value; } public IActionResult Index() { string portstr = StarInfoConfig.Port.ToString(); string jobname = JobConfig.Name; string liststr = ""; JobListConfig.ForEach(item => { liststr += item.Name + "," + item.Age + "," + item.Sex + "|||||"; }); ViewBag.portstr = portstr; ViewBag.jobname = jobname; ViewBag.liststr = liststr; return View(); } }
6.输出结果
点击下载代码
相关文章推荐
- 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
- IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题
- ASP.NET Core读取appsettings.json的配置
- ASP.NET Core读取appsettings.json的配置
- 【无私分享:ASP.NET CORE 项目实战(第六章)】读取配置文件(一) appsettings.json
- ASP.NET CORE入门之读取Json配置文件
- 菜鸟入门【ASP.NET Core】5:命令行配置、Json文件配置、Bind读取配置到C#实例、在Core Mvc中使用Options
- asp.net core 获取 appsettings.json 配置
- .NET Core在类库中读取配置文件appsettings.json
- ASP.NET core Web中使用appsettings.json配置文件的方法
- 【ASP.NET Core快速入门】(五)命令行配置、Json文件配置、Bind读取配置到C#实例、在Core Mvc中使用Options
- ASP.NET CORE入门之读取Json配置文件
- asp.net core轻松入门之MVC中Options读取配置文件
- 用"hosting.json"配置ASP.NET Core站点的Hosting环境
- 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件
- 【无私分享:ASP.NET CORE 项目实战(第八章)】读取配置文件(二) 读取自定义配置文件
- ASP .NET CORE 读取配置文件的方法
- ASP.NET Core实现类库项目读取配置文件
- ASP.NET Core 注入和获取 AppSettings 配置
- 2.1命令行和JSON的配置「深入浅出ASP.NET Core系列」