- Continue with the previous section, and then use options or bind to convert the configuration in the JSON file into C # entities and map them to each other. Start by creating an ASP. NET Core MVC Project Optionsbindsample
- Startup.cs, here, use dependency injection to add the configuration in.
1 Public Get Set ; } 2 3 Public Startup (iconfiguration configuration) 4 {5this . Configuration = configuration; 6 }
- and build a Class.cs.
1 Public classClass2 {3 Public intClassno {Get;Set; }4 Public stringClassdesc {Get;Set; }5 PublicList<student> Students {Get;Set; }6 }7 8 Public classStudent9 {Ten Public stringName {Get;Set; } One Public stringAge {Get;Set; } A}
- Build another Appsettings.json (name must be called this, because in Program.cs webhost.createdefaultbuilder (args) reads the Appsettings.json file by default)
1 {2 "Classno":"1",3 "Classdesc":"ASP. NET Core 101",4 "Students": [5 {6 "name":"Liuxh",7 " Age":" to"8 },9 {Ten "name":"LINHJ", One " Age":" to" A }, - { - "name":"Liuxy", the " Age":"7" - - - + }, - { + "name":"Liuss", A " Age":"1" at } - ] - -}
- The last Starup.cs code is this
PublicIConfiguration Configuration {Get;Set; } PublicStartup (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, visithttps://go.microsoft.com/fwlink/?LinkID=398940 Public voidconfigureservices (iservicecollection services) {}//This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env) {if(env. Isdevelopment ()) {app. Usedeveloperexceptionpage (); } app. Run (Async(context) = { varMyClass =NewClass (); Configuration.bind (myClass);//map the information and objects of the configuration file . awaitContext. Response.writeasync ($"Classno:{myclass.classno}"); awaitContext. Response.writeasync ($"Classdesc:{myclass.classdesc}"); awaitContext. Response.writeasync ($"{MyClass.Students.Count} Students"); }); }
- Finally start the web site
(12) Bind read configuration to C # instance