. NET core 2.0 MVC get configuration information

Source: Internet
Author: User

Mvc_core_config

在.net core mvc中 配置文件格式更改为json且移除了ConfigurationManager.AppSettings[xmlkey]的方法,那么,如何来获取配置信息呢?

The first step is to add the JSON file to the application

<default code> public static void Main (string[] args) {buildwebhost (args).    Run (); } public static Iwebhost Buildwebhost (string[] args) = Webhost.createdefaultbuilder (args). Usestartup<startup> ().      Build (); If you use the default method to start, you can skip this step <reason> view the source code in the Createdefaultbuilder method has been used to add profile//configuration information Processing--for the second step of the read configuration info . Configureappconfiguration ((Action<webhostbuildercontext, iconfigurationbuilder>) ((hostingContext, config) =              > {//Inject operating environment ihostingenvironment hostingenvironment = hostingcontext.hostingenvironment; Load configuration file CONFIG. Addjsonfile ("Appsettings.json", True, true). Addjsonfile (String. Format ("appsettings.{          0}.json ", (object) hostingenvironment.environmentname), True, true); Load the appropriate file according to the running environment if (hostingenvironment.isdevelopment ()) {Assembly Assembly = ASSEMBLY.L Oad (New AssemblyName (Hostingenvironment.applicationname));              if (assembly! = (assembly) null) CONFIG.            Addusersecrets (assembly, true); } config.            Addenvironmentvariables ();            if (args = = null) return; Config.      Addcommandline (args); }) To customize the Add profile please refer to the above code

Second Step reading configuration information

<code>    <Startup>    //由于在程序启动时已经配置了configuration 则可以直接通过构造方法获取配置信息    public Startup(IConfiguration configuration)    {        Configuration = configuration;    }    public IConfiguration Configuration { get; }

The third step is to get the configuration information in the controller

<code> <Startup> <method-configureservices>//Add options services.        AddOptions (); Use the configuration information for Di injection services. Configure<appsetting> (Configuration.getsection (nameof (appsetting));< related method notes > Getsection:key-value The value is similar to the dictionary value operation Configure: Di injection Key code://di injection Addsingleton global share a ioption The type services that correspond to the schangetokensource<toptions> injection parameters.                 Addsingleton<ioptionschangetokensource<toptions>> ((ioptionschangetokensource<toptions>)            New configurationchangetokensource<toptions> (name, config)); That is, actually using Addsingleton injection to achieve <source code>//<summary>//registers a Configuratio n instance which toptions would bind against. Bind the configuration instance as option to the parameter///</summary>//<typeparam name= "toptions" >the type of options be ING Configured.</typeparam>//<param name= "Services" >the <see cref= "T:microsoft.extensions.dependenc Yinjection.iservicecollection "/> To add the services to.</param>//<param name=" config ">the c Onfiguration being bound.</param>//<returns>the <see cref= "T:microsoft.extensions.dependencyi Njection. Iservicecollection "/> So, additional calls can be chained.</returns> public static Iservicecollec            tion configure<toptions> (This iservicecollection services, iconfiguration config) where toptions:class {return services.            Configure<toptions> (Microsoft.Extensions.Options.Options.DefaultName, config);            }//<summary>//registers a configuration instance which toptions would bind against. Ibid. </summary>//<typeparam name= "toptions" >the type of options being Configured.</typ Eparam>            <param name= "Services" >the <see cref= "T:microsoft.extensions.dependencyinjection.iservicecollecti On "/> To add the services to.</param>//<param name=" name ">the name of the options instance.& lt;/param>//<param name= "config" >the configuration being bound.</param>//<re Turns>the <see cref= "t:microsoft.extensions.dependencyinjection.iservicecollection"/> so that additional Calls can chained.</returns> public static iservicecollection configure<toptions> (This ISERVICEC Ollection Services, string name, IConfiguration config) where Toptions:class {if (services = = N              ull) throw new ArgumentNullException (nameof (services));                    if (config = = null) throw new ArgumentNullException (nameof (config)); Perform di injection Addsingleton globally share a type that corresponds to a ioptionschangetokensource<toptions> injection parameter                     Services. Addsingleton<ioptionschangetokensource<toptions>> ((ioptionschangetokensource<toptions>) New              configurationchangetokensource<toptions> (name, config)); Return services. Addsingleton<iconfigureoptions<toptions>> ((iconfigureoptions<toptions>) New            namedconfigurefromconfigurationoptions<toptions> (name, config));  } <Controller> public abstract class Basecontroller:controller {protected appsetting            appsetting {get; set;} Protected Basecontroller (ioptions<appsetting> option) = appsetting = option.        Value; } intro: Since the configuration information is often used in MVC, I encapsulate the related processing of getting configuration information in an abstract controller, so I just need to inherit this controller from the controller with configuration information and then get the configuration information through appsetting in the controller.

Extension description

在Startup中直接获取配置文件:public Startup(IApplicationEnvironment appEnv, IHostingEnvironment env) {   _config = new ConfigurationBuilder()            .AddJsonFile("config.json")            .AddJsonFile("appsettings.json")        .AddEnvironmentVariables()        .Build();}[https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration](https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.1&tabs=basicconfiguration "官方教程")

Note: The appsetting that I use is the entity class that corresponds to my configuration information "can be named according to the actual situation"

欢迎各位大佬评论并指出我的错误 :)

Author:monster

since:6/4/2018 11:12:45 AM

Direction:.net Core 2.0 MVC configuration file Usage

. NET core 2.0 MVC get configuration information

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.