(十二)Bind读取配置到C#实例

  • 继续上一节的,接下来用Options或者Bind把json文件里的配置转成C#的实体,相互之间映射起来。首先新建一个asp.net core mvc项目OptionsBindSample
  • Startup.cs,这里用依赖注入把Configuration加进来
  • 1         public IConfiguration Configuration { get; set; }
    2 
    3         public Startup(IConfiguration configuration)
    4         {
    5             this.Configuration = configuration;
    6         }

     

  • 再建立一个Class.cs
  •  1 public class Class
     2         {
     3             public int ClassNo { get; set; }
     4             public string ClassDesc { get; set; }
     5             public List<Student> Students { get; set; }
     6         }
     7 
     8         public class Student
     9         {
    10             public string Name { get; set; }
    11             public string Age { get; set; }
    12         }

     

  • 再建一个appsettings.json(名称一定要叫这个,因为在Program.cs中WebHost.CreateDefaultBuilder(args)会默认读取appsettings.json文件)
  •  1 {
     2   "ClassNo": "1",
     3   "ClassDesc": "ASP.NET Core 101",
     4   "Students": [
     5     {
     6       "name": "liuxh",
     7       "age": "31"
     8     },
     9     {
    10       "name": "linhj",
    11       "age": "31"
    12     },
    13     {
    14       "name": "liuxy",
    15       "age": "7"
    16 
    17 
    18 
    19     },
    20     {
    21       "name": "liuss",
    22       "age": "1"
    23     }
    24   ]
    25 
    26 }

     

  • 最后Starup.cs代码是这样的
  •         public IConfiguration Configuration { get; set; }
    
            public Startup(IConfiguration configuration)
            {
                this.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);//把配置文件的信息和对象映射起来
    
                    await context.Response.WriteAsync($"ClassNo:{myClass.ClassNo}");
                    await context.Response.WriteAsync($"ClassDesc:{myClass.ClassDesc}");
                    await context.Response.WriteAsync($"{myClass.Students.Count} Students");
    
                }); 
            }

     

  • 最后启动网站
posted @ 2018-05-18 21:31  liu_xh  阅读(1107)  评论(0编辑  收藏  举报