首先新建一个ASP.NET Core空项目,命名为BindReader
然后 向项目中添加一个名为appsettings.json的json文件,为什么叫appsettings呢? 打开Program.cs
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
代码中的IWebHost在启动时,具有自动加载appsettings.json的特性,所以命名成这个就不用特意地加载了。
然后再appsetting.json中写入数据,数据如下:
{ "Name": "pragram language", "Items": [ { "Language": "C#", "Tool": "visual studio" }, { "Language": "JAVA", "Tool": "Elcipse" } ] }
在项目中添加一个Class的类,根据该json文件的结构,创建Clsaa类中的内容,注意Class中的字段名称和Json中的字段名称必须要个匹配,一一对应。
Claa类中的代码如下:
public class Class { public String Name { get; set; } public List<Item> Items { get; set; } } public class Item { public string Language { get; set; } public string Tool { get; set; } }
可以看到字段与Json内的数据时一一对应的。
打开startup.cs文件
修改startup.cs的构造函数并添加Connection属性
public IConfiguration Configuration { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; }
实例化一个Class类
var myClass = new Class();
通过connection将配置文件中的数据来绑定Class实例
Configuration.Bind(myClass);
数据展现
Console.WriteLine($"name:{myClass.Name}"); Console.WriteLine(); for (int i = 0; i < myClass.Items.Count; i++) { await context.Response.WriteAsync($"language:{myClass.Items[i].Language}"); await context.Response.WriteAsync($"tool:{myClass.Items[i].Tool}"); }
总体的startup.cs中的代码如下:
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.Configuration; using Microsoft.Extensions.DependencyInjection; namespace BindReader { public class Startup { 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 con = new ConfigurationBuilder().AddJsonFile("appsettings.json"); //Configuration = con.Build(); var myClass = new Class(); Configuration.Bind(myClass); Console.WriteLine($"name:{myClass.Name}"); Console.WriteLine(); for (int i = 0; i < myClass.Items.Count; i++) { await context.Response.WriteAsync($"language:{myClass.Items[i].Language}"); await context.Response.WriteAsync($"tool:{myClass.Items[i].Tool}"); } await context.Response.WriteAsync("Hello World!"); }); } } }
以上完整github项目代码地址:https://github.com/liuzhenyulive/BindReader
有任何疑问可以在评论区留言。