1.建立一個空的ASP.NET Core Web 應用程序json
2.程序包管理控制檯執行Install-Package Microsoft.AspNetCore -Version 2.0.1app
3.建立json文件命名爲:appsettings.json,再添加一個Class類async
appsettings.json內容爲:ui
{ "ClassNo": "1", "ClassDesc": "ASP.NET Core 101", "Students": [ { "name": "name1", "age": "12" }, { "name": "name2", "age": "13" }, { "name": "name13", "age": "14" } ] }
Class 類代碼this
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OptionsBindSample { public class Class { public int ClassNo { get; set; } public string ClassDesc { get; set; } public List<Student> Students { get; set; } } public class Student { public string Name { get; set; } public string Age { get; set; } } }
4.Startup.cs 編寫讀取配置構造方法,並在app.Run方法打印,代碼以下spa
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace OptionsBindSample { public class Startup { /// <summary> /// 添加構造方法用來獲取配置信息 /// </summary> public IConfiguration Configuration { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Run(async (context) => { var myClass = new Class(); Configuration.Bind(myClass);//綁定基礎信息 //輸出json配置到頁面 await context.Response.WriteAsync($"ClassNo {myClass.ClassNo}"); await context.Response.WriteAsync($"ClassDesc {myClass.ClassDesc}"); await context.Response.WriteAsync($"myClass Count {myClass.Students.Count}"); }); } } }
5.啓動程序,輸出結果code