Beginner's introductory "ASP." 5: Command line configuration, JSON file configuration, bind read configuration to C # instances, using options in Core MVC

Source: Internet
Author: User

Command line configuration We create a console project from vs2017 commandlinesample

You can see that since the project is dotnet Core Framework we need it. ASP. We can add the Microsoft.AspNetCore.All directly

After the installation is complete, we can make subsequent configuration through using Microsoft.Extensions.Configuration;
Static voidMain (string[] args) {            varBuilder =NewConfigurationbuilder ()//Initialize a configurationbuilder. Addcommandline (args);//extension Functions             varConfiguration = Builder. Build ();//get the configuration .//see what's Inside the configurationConsole.WriteLine ($"name:{configuration["Name"]}"); Console.WriteLine ($"age:{configuration["Age"]}");        Console.ReadLine (); }
This time the direct execution will not have the result, because we do not configure the configuration we can be in the debug parameter configuration, the operation result configuration is generally in the form of key-value pairs, if we want to pass him the default parameters, Can be passed with a dictionary, and then added in the form of memory
usingSystem;usingSystem.Collections.Generic;usingMicrosoft.Extensions.Configuration;namespacecommandlinesample{classProgram {Static voidMain (string[] args) {            varSettings =Newdictionary<string,string>            {                {"name","rookie takeoff ."},                {" Age"," -"}            }; varBuilder =NewConfigurationbuilder ()//Initialize a configurationbuilder. Addinmemorycollection (Settings)//Add in memory form. Addcommandline (args);//extension Functions             varConfiguration = Builder. Build ();//get the configuration .//see what's Inside the configurationConsole.WriteLine ($"name:{configuration["Name"]}"); Console.WriteLine ($"age:{configuration["Age"]}");        Console.ReadLine (); }    }}
This time we can be debugging inside the parameters removed, directly start the project with the console, you can see the delivery parameters and do not pass parameters will have different configuration display effect JSON file configuration new Console project Jsonconfigsample we need it. asp. NET Core Reference, We can add Microsoft.AspNetCore.All directly and then create a new JSON file Class.json and build to the bin
{  "Classno":"1",  "Classdesc":"Beginner's Introductory ASP .",   "Students": [    {      "name":"Lao Wang",      " Age":" -"    },    {      "name":"Lao Li",      " Age":" -"    },    {      "name":"Old Bull",      " Age":" -"    }  ]}

Then read the Class.json file and read the results

Bind read Configuration to a C # instance new console project Optionsbindsample

Choose an empty template this time the creation of the Startup.cs file does not have the configuration, because we want to use the configuration, so we need to use the dependency injection, Add the configuration and we can use the configuration in Startup.cs. New Class.class Class
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;namespaceoptionsbindsample{ Public classClass { Public intClassno {Get;Set; }  Public stringClassdesc {Get;Set; }  PublicList<student> Students {Get;Set; } }      Public classStudent { Public stringName {Get;Set; }  Public stringAge {Get;Set; } }}
Add an ASP. NET config file Appsettings.json
{  "Classno":"1",  "Classdesc":"Beginner's Introductory ASP .",   "Students": [    {      "name":"Lao Wang",      " Age":" -"    },    {      "name":"Lao Li",      " Age":" -"    },    {      "name":"Old Bull",      " Age":" -"    }  ]}
Why do you want to add a configuration file? We can see: Because the default is not to add the configuration file when the webhost is started, but when the project starts, We will read the contents of Appsettings.json to the configuration by default, by Createdefaultbuilder this method to load them into the At this time we can Startup.cs read the appsetting configuration to the corresponding class instantiation model, and print out, after running the actual bar effect, the format of the display is forgotten, you can try to tune a tune

Adding MVC middleware using options in core MVC (middleware) First, we create a new folder in the previous Optionsbindsample project: Controllers, Views. Add a HomeController. Add the index view to the index action for HomeController, and then comment out the following in Startup.cs, because if you do not annotate the pipeline will always be occupied, causing our MVC to be inaccessible Then add MVC in the Startup.cs configureservices method and then configure the use MVC default route in the Startup.cs configure method

The controller dependency injection injects MyClass into the homecontroller in a way that relies on injection. Just this time we can't use Bing's method, but use the ioption<t> generic method to inject the class in

This time we return to the strongly typed view

After dependency injection and view completion, We're going to register Class to options in Startup.cs's Configureservices method, pass the configuration in, so that HomeController calls Ioptions<class > will be able to get the class content from the configuration

Effect after start

"Small extension": We can also take the injection directly out, through the dependency injection framework directly in the view of the new controller Home2controller, do not need to add any dependency injection configuration. Create an index view that references iotions<t> directly in the view injected in a strongly typed view

Run effect

Talking about the Buildwebhost method in Program.cs when we create an MVC project, the Buildwebhost in the auto-created Program.cs is the following, and cannot be modified by accessing the other *,json configuration file to read the specific *.json configuration file

Beginner's introductory "ASP." 5: Command line configuration, JSON file configuration, bind read configuration to C # instances, using options in Core MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.