"ASP. NET Core QuickStart" (v) 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 through vs2017 commandlinesample






You can see the dotnet core framework since the project is now






We need it. The ASP. NET Core reference comes in, we can add Microsoft.AspNetCore.All directly






After the installation is complete, we can make subsequent configuration through using Microsoft.Extensions.Configuration;





using System;
using Microsoft.Extensions.Configuration;

namespace CommandLineSample
{
     class Program
     {
         static void Main (string [] args)
         {
             var builder = new ConfigurationBuilder () // Initialize a ConfigurationBuilder
                 .AddCommandLine (args); // Extended function

             var configuration = builder.Build (); // Get the configuration

             // See what's in the configuration
             Console.WriteLine ($ "name: {configuration [" name "]}");
             Console.WriteLine ($ "age: {configuration [" age "]}");

             Console.ReadLine ();
         }
     }
} 
View Code


The direct execution will not result, as we do not configure the configuration






We can configure the parameters in the debug






Run results






The configuration is usually in the form of a key-value pair, and if we want to pass the default argument to him, we can use a dictionary to pass it, and then add it in the form of memory.





using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;

namespace CommandLineSample
{
     class Program
     {
         static void Main (string [] args)
         {
             var settings = new Dictionary <string, string>
             {
                 {"name", "wyt"},
                 {"age", "18"}
             };


             var builder = new ConfigurationBuilder () // Initialize a ConfigurationBuilder

                 .AddInMemoryCollection (settings) // Added in the form of memory

                 .AddCommandLine (args); // Extended function

             var configuration = builder.Build (); // Get the configuration

             // See what's in the configuration
             Console.WriteLine ($ "name: {configuration [" name "]}");
             Console.WriteLine ($ "age: {configuration [" age "]}");

             Console.ReadLine ();
         }
     }
} 
View Code


At this point, we can remove the parameters from the Debug.



Start a project directly with the console






You can see that passing parameters and not passing parameters have different configuration display effects


JSON file configuration


New Console Project Jsonconfigsample



We need it. The ASP. NET Core reference comes in, we can add Microsoft.AspNetCore.All directly



Then create a new JSON file Class.json and build to the bin


 
{ "ClassNo": "1", "ClassDesc": "ASP.NET Core 101", "Students": [
    { "name": "jesse", "age": "13" },
    { "name": "wyt", "age": "18" },
    { "name": "zzz", "age": "12" }
  ]
}


Then read the Class.json file






Read results





Bind read configuration to C # instance


New Console Project Optionsbindsample






Select an empty template






There is no configuration in the Startup.cs file created at this time






Since we're going to use the configuration, we're going to use dependency injection to add the configuration in.






This time we can use the configuration in the Startup.cs.



New Class.class Class class


 
 
public class Class
    {
        public int ClassNo { get; set; }

        public string ClassDesc { get; set; }

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

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

        public string Age { get; set; }
    }
View Code


Add an ASP. NET config file Appsettings.json


 
 
{
  "ClassNo": "1",
  "ClassDesc": "ASP.NET Core 101",

  "Students": [
    {
      "name": "jesse",
      "age": "13"
    },
    {
      "name": "wyt",
      "age": "18"
    },
    {
      "name": "zzz",
      "age": "12"
    }
  ]
}
View Code


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 bind the read appsetting configuration to the corresponding class instantiation model in Startup.cs and print it out






After running the reality bar effect





Adding MVC middleware with options in core MVC (middleware)


First, we create a new folder in the previous Optionsbindsample project: Controllers, Views. Add a HomeController. Add an index view to the index action of HomeController






Next, 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 Configureservices method of the Startup.cs






Next, configure the use MVC default route in the Startup.cs configure method





Controller Dependency Injection


Inject 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 display


New controller Home2controller, no 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 created the MVC project, the Buildwebhost in the auto-created Program.cs was the following, and could not access the other *,json configuration files






We can modify it to read a specific *.json configuration file









"ASP. NET Core QuickStart" (v) command line configuration, JSON file configuration, bind read configuration to C # instances, using options in core MVC


Related Article

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.