[ASP.net Core] are two ways to read the application configuration file appsettings.json

Reading config in ASP.net Core

Foreword

Just getting started with ASP.net Core encounter confusing one point: there is no Web.config configuration file, the previous connectionStrings, appSettings do not know how to set and read

This article briefly explain

practice

※ This article is an example of ASP.net Core 2.1 version

ASP.net Core application configuration file instead appsettings.json, content json format

Right from the project → → adding new projects

Search keyword "application" can find, add it to the project path to the root

Name to maintain appsettings.json better not change it, because with the Program.cs file in the WebHost.CreateDefaultBuilder () concerning

Then he wrote the following data in appsettings.json

※ attention ASP.net Core 2.1, Visual Studio 2017 15.8.3ver, the default file added appsettings.json not UTF-8 encoding format, so I do not support Chinese, want to support the Chinese have a way to get out of trouble (or continue to wait for Microsoft revised XD) , please read the article below

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Email": "[email protected]",
  "ThemeColor": "red",
  "isRunSSL": true,
  "MaxNumber": 10
}

If you have to use Entity Framework Core to read the database connection string, please refer to my other article ↓

[ASP.net Core 2] using the Entity Framework Core 2 Database First embodiment access data (model data items separated in ClassLibrary)

The configuration file is read way, mainly in two ways

1. Similarly previously WebConfigurationManager, return to the reading mode Key Value (using IConfiguration Interface)

See Controller ↓ Sample Code of

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; 
using Microsoft.Extensions.Options;
using StarterM.Models;
/*引用命名空间*/
using Microsoft.Extensions.Configuration;

namespace StarterM.Controllers
{
    public class HomeController : Controller
    {
        
        private readonly IConfiguration _config;//这很像ASP.net的WebConfigurationManager
        //在构造函数使用相依性注入建立IConfiguration
        public HomeController(IConfiguration config)
        {
            this._config = config; 
        }

        public IActionResult Index()
        {
            ViewBag.config = this._config;
            return View();
        }
    }
}

View↓

 
@using Microsoft.Extensions.Configuration  
 
@{
    Layout = null;
} 
 


     

 
    @{
        IConfiguration config = (IConfiguration)ViewBag.config; 
    
  
  
  • DefaultConnection: @config.GetConnectionString("DefaultConnection")
  • Email: @(config.GetValue ("Email"))
  • ThemeColor: @(config.GetValue ("ThemeColor"))
  • isRunSSL: @(config.GetValue ("isRunSSL"))
  • MaxNumber: @(config.GetValue ("MaxNumber"))
}

The results ↓

2. strongly typed read mode

In accordance with JSON content to establish a class on their own, if you do not know how to set up, then went to the site to appsettings.json json2csharp in the JSON content posted up

The following is my new class file ↓

接着要把appsettings.json里的数据倒进刚刚声明的类里,在Startup.cs↓

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StarterM.Models;

namespace StarterM
{
    public class Startup
    {
        /// 
        /// 读取 appsettings.json 专用 
        /// 
        public IConfiguration _config { get; }
        public Startup(IConfiguration config)
        {
            this._config = config;
        } 
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(); 
            //加这行
            services.Configure
  
  
   
   (this._config); 
        } 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
             
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();

        }
    }
}

  
  

Controller↓

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
/*引用命名空间*/
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;//加这行
using StarterM.Models;

namespace StarterM.Controllers
{
    public class HomeController : Controller
    {

        private readonly IOptions
  
  
   
    _opt; //加这行
        private readonly IConfiguration _config;
        //使用相依性注入
        public HomeController(IOptions
   
   
    
     opt, IConfiguration config)
        {
            this._config = config;
            this._opt = opt;//加这行
        }

        public IActionResult Index()
        {
            ViewBag.config = this._config;
            MyAppConfig objConfig = this._opt.Value;//注意这行
            ViewBag.ObjConfig = objConfig;
            return View();
        }
    }
}
   
   
  
  

View↓

@using StarterM.Models

  
  
@using Microsoft.Extensions.Configuration
@{
    Layout = null;
}



    



    
  
  
↓使用强类型对象读取应用程序配置文件案
@{ MyAppConfig objConfig = (MyAppConfig)ViewBag.ObjConfig;
  • DefaultConnection: @objConfig.ConnectionStrings.DefaultConnection
  • Email: @objConfig.Email
  • ThemeColor: @objConfig.ThemeColor
  • isRunSSL: @objConfig.isRunSSL
  • MaxNumber: @objConfig.MaxNumber
}
↓使用IConfiguration读取应用程序配置文件案
@{ IConfiguration config = (IConfiguration)ViewBag.config;
  • DefaultConnection: @config.GetConnectionString("DefaultConnection")
  • Email: @(config.GetValue ("Email"))
  • ThemeColor: @(config.GetValue ("ThemeColor"))
  • isRunSSL: @(config.GetValue ("isRunSSL"))
  • MaxNumber: @(config.GetValue ("MaxNumber"))
}

执行结果↓

刚才有提过,默认appsettings.json由于不是UTF-8编码,所以如果有下面的中文内容

执行结果就会变成乱码↓

解决办法:先用记事本notepad开启appsettings.json档,然后变更使用UTF-8编码后再覆盖存档。

重新建置项目后再执行一次网页,中文就可以正常显示了~

最后留意一下,如果采用强类型对象读取appsettings.json方式,由于组态数据注入对象时间点的关系

网站发布到IIS后如果有修改appsettings.json的话,记得IIS站台要重新启动才会生效

※使用IConfiguration读取appsettings.json的话,则无需此动作

※2019.4.8追记:.Net Core Console貌似无法从项目直接加入appsettings.json,那就手动自己加入吧XD

请参考:[.Net Core] 在.Net Core Console中读取应用程序组态档 appsettings.json

自行从Nuget把 Microsoft.Extensions.Configuration.Json 加入参考后,照着程序写,就可以读取appsettings.json

原文:大专栏  [ASP.net Core] 两种方式读取应用程序配置文件 appsettings.json


Guess you like

Origin www.cnblogs.com/chinatrump/p/11505334.html