[ASP.net Core] 將AppSettings 設定儲存於JSON 檔中.

在ASP.net Core 中並沒有如.net framework 中預設設定於web.config 或app.config 中, 須要人手設定, 雖然有少許不便, 但換來了更lightweight 又更有彈性的部署. 示範中會以將EF 中的connection string 修改存於JSON 檔, 令其更configurable.

因為會涉及profile 設定, 所以亦會在此亦會分享.net core 中profiling 的相關設定.

在ASP.net Core 中, profile 設定於Project Property > Debug 中. 與.net framework 比較, 不用修改project file, 相對的容易.

加入設定方法如下.

  1. 建立JSON設定.
    於Appsettings.{environment}中, 加入以下JSON 設定.

    "AppSettings": {
        "DefaultDataSourceConnectionString": "<<ConnectionString>>"
    }
  2. 建立Setting class.
    建立一個新class 命名為AppSettings, 並輸入以下代碼.

    public class AppSettings
        {
            public string DefaultDataSourceConnectionString { get; set; }
        }
  3. 設定啟動時讀取JSON 檔.
    開啟Program.cs, 修改代碼如下.

    public class Program
        {
            public static void Main(string[] args)
            {
                CreateWebHostBuilder(args).Build().Run();
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((builderContext, config) =>
                {
                    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
                    config.AddJsonFile(@"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                    config.AddEnvironmentVariables();
                })
                .UseStartup<Startup>();
        }
  4. 將設定放入class 中.
    開啟Startup.cs, 修改ConfigureService() 如下.

    // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
                services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
            }
  5. 建立Base Controller 存取設定.
    建立abstract class CustomContrllerBase, 並輸入以下代碼.

    public abstract class CustomControllerBase : ControllerBase
        {
            protected readonly AppSettings configuration;
            public CustomControllerBase(IOptions<AppSettings> options)
            {
                configuration = options.Value;
            }
        }
  6. 修改EF context, 使其可以存取json 檔設定.
    開啟DBContext.cs, 修改代碼如下.

    public partial class TestDBContext : DbContext
        {
    private readonly AppSettings configuration;
    public TestDBContext(AppSettings configuration) {
                this.configuration = configuration;
            }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                if (!optionsBuilder.IsConfigured)
                {
                    optionsBuilder.UseSqlServer(configuration.DefaultDataSourceConnectionString);
                }
            }
    }
  7. 建立Controller.
    建立新API empty controller, 命名為DepartmentController, 並輸入代碼如下.

    [Route("api/[controller]")]
        [ApiController]
        public class DepartmentController : CustomControllerBase
        {
            public DepartmentController(IOptions<AppSettings> options) : base(options) { }
    
            [HttpGet("findAll/{includeInactiveItems}")]
            public async Task<IList<Department>> FindAllAsync(bool includeInactiveItems = false) {
                IList<Department> result = new List<Department>();
                using (OrganizationContext context = new OrganizationContext(this.configuration))
                {
                    IQueryable<Department> query= context.Department;
                    if (!includeInactiveItems) {
                        query = query.Where(o => o.IsActive == true);
                    }
                    result = await query.ToListAsync();
                }
                return result;
            }
        }
  8. 測試.
    在project 中按F5 執行程式, 輸入網址後若見到以JSON 格式傳回資料, 代表測試成功.
About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.