ASP.NET Core 2 外掛設定檔


上圖是一般開發 WinForm/APP 時會使用一些設定檔,提供程式一定的彈性,其用法是會把設定檔資訊設定 Properties 屬性裡面的『設定』,而實際會存在 app.config 或是 user.config 裡面,而且是使用XML格式儲存的(如上圖)。

但在ASP.NET Core 2 下如果要使用自己的設定檔,它的使用方式和一般 WinForm/APP 不一樣,因為它沒有預設的介面可以設定,而且它不能儲存 user.config,它反而比較建議使用 JSON 格式來處理設定檔。

畢竟JSON格式是網路上比較通用的格式,處理與閱讀起來也比XML輕鬆。

如果在系統上要一開始就載入設定檔,必需要先建立一個 json 檔案,
例如在程式 root 下新增一個 json 檔,並設定內容:


然後新增 json 檔案內容並儲存


它的結構基本上會像下面:

{
  "Section" : { "Name" : Value }
}


一個 json 裡面可以有許多 section ,每個 section 裡面可以包含多組 name : value


然後在 Program.cs 裡面使用 ConfigureAppConfiguration 增加組態設定,
(這個 ConfigureAppConfiguration 本身就是一種 DI)

Program.cs
namespace MyWeb1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((webHostBuilder, configurationBinder) => {
                //外掛json設定檔
                configurationBinder.AddJsonFile("mySettings.json", optional: true);
            })
                .UseStartup<Startup>();
    }
}


然後,在需要用到組態檔的類別裡面 使用 DI 取回,例如我在 Startup.cs 使用組態檔,然後可以對組態檔進行讀取與設定。

Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace MyWeb1
{
    public class Startup
    {
        private readonly IConfiguration _config;
        //在建構時注入組態檔
        public Startup(IConfiguration config)
        {
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World! <br />");

                await context.Response.WriteAsync("ConnectionStrings = " + _config.GetConnectionString("ConnectionStrings") + "<br />");

                await context.Response.WriteAsync("RunStart.DetectPath = " + _config.GetSection("RunStart")["DetectPath"] + "<br />");

                await context.Response.WriteAsync("RunStart.DecectInterval = " + _config.GetSection("RunStart")["DecectInterval"] + "<br />");

                await context.Response.WriteAsync("RunStart.LogFile = " + _config.GetSection("RunStart")["LogFile"] + "<br />");

                //修改設定值
                _config.GetSection("RunStart")["DecectInterval"] = "22";

                await context.Response.WriteAsync("new RunStart.DecectInterval = " + _config.GetSection("RunStart")["DecectInterval"] + "<br />");
            });
        }
    }
}


在上面案例中先在 Startup 的建構函數取用 IConfiguration 的服務到 _config,然後在 app.Run 裡面讀取 _config。

這個 IConfiguration 有個預設的方法 GetConnectionString 這個方法,這方法預設就是讀取名稱為  "ConnectionStrings" 的 section 。

如要取用其它 section 就要用 GetSetcion("section")[name] 的方式取用,要注意它取用的資料一律都是以 string 回傳。

當然也可以變更 section.name 的內容,但是它必須以 string 去設定,而且無法回存原本的 json 檔案!!

其它:
如果把 json 建立在其它資料夾下的話,例如 properties 資料夾下:
記得在導入ConfigureAppConfiguration 時要使用相對應的路徑:



        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((webHostBuilder, configurationBinder) => {
                //外掛json設定檔
                configurationBinder.AddJsonFile("properties\\mySettings.json", optional: true);
            })
                .UseStartup<Startup>();




留言

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式