Bind读取配置到C#实例

2021-04-22 14:26

阅读:405

1.创建一个空的ASP.NET Core Web 应用程序

2.程序包管理控制台执行Install-Package Microsoft.AspNetCore -Version 2.0.1

3.创建json文件命名为:appsettings.json,再添加一个Class类

appsettings.json内容为:

{
  "ClassNo": "1",
  "ClassDesc": "ASP.NET Core 101",
  "Students": [
    {
      "name": "name1",
      "age": "12"
    },
    {
      "name": "name2",
      "age": "13"
    },
    {
      "name": "name13",
      "age": "14"
    }
  ]
}

Class 类代码

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 Students { get; set; }
    }

    public class Student
    {
        public string Name { get; set; }
        public string Age { get; set; }
    }
}

4.Startup.cs 编写读取配置构造方法,并在app.Run方法打印,代码如下

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
    {
        /// 
        /// 添加构造方法用来获取配置信息
        /// 
        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.启动程序,输出结果

技术分享图片

 


评论


亲,登录后才可以留言!