asp.net core 读取appsettings.json配置项
1.新建一个asp.net core 项目
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.输出结果