1. 程式人生 > >(十二)Bind讀取配置到C#實例

(十二)Bind讀取配置到C#實例

public bin 裏的 VC student pset sting get nds

  • 繼續上一節的,接下來用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");
    
                }); 
            }

  • 最後啟動網站

(十二)Bind讀取配置到C#實例