在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, 相對的容易.
加入設定方法如下.
- 建立JSON設定.
於Appsettings.{environment}中, 加入以下JSON 設定."AppSettings": { "DefaultDataSourceConnectionString": "<<ConnectionString>>" }
- 建立Setting class.
建立一個新class 命名為AppSettings, 並輸入以下代碼.public class AppSettings { public string DefaultDataSourceConnectionString { get; set; } }
- 設定啟動時讀取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>(); }
- 將設定放入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")); }
- 建立Base Controller 存取設定.
建立abstract class CustomContrllerBase, 並輸入以下代碼.public abstract class CustomControllerBase : ControllerBase { protected readonly AppSettings configuration; public CustomControllerBase(IOptions<AppSettings> options) { configuration = options.Value; } }
- 修改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); } } }
- 建立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; } }
- 測試.
在project 中按F5 執行程式, 輸入網址後若見到以JSON 格式傳回資料, 代表測試成功.
Leave a Reply