首页 > 其他 > 详细

12-optionBinding

时间:2018-07-10 01:08:21      阅读:279      评论:0      收藏:0      [点我收藏+]

1-创建一个空的dotnet mvc网站

2- 创建appsettings.json文件, 这文件会默认被绑定

{
  "ClassNo": "1",
  "ClassDesc": "Asp.net core",
  "Students": [
    {
      "name": "lili",
      "age": "11"
    },
    {
      "name": "xiaofeng",
      "age": "33"
    },
    {
      "name": "xiaobao",
      "age": "66"
    }
  ]
}

  3-创建一个可映射的class类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace optionBindingDemo
{
    public class Classes
    {
        public string ClassNo { get; set; }

        public string ClassDesc { get; set; }

        public List<Student> Students { get; set; }
    }

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

4-开始绑定

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 optionBindingDemo
{
    public class Startup
    {
        IConfiguration Configuration;
        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();
            }
            Classes cls = new Classes();
            this.Configuration.Bind(cls);
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync($"ClassNo: {cls.ClassNo}");
                await context.Response.WriteAsync($"ClassDesc: {cls.ClassDesc}");
                await context.Response.WriteAsync($"studentListCount: {cls.Students.Count}");
            });
        }
    }
}

 

12-optionBinding

原文:https://www.cnblogs.com/qinzb/p/9286809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!