1

我們正在使用webApi作爲我們最新的產品之一,這些產品託管在IIS7.5上並以ASP.NET5(.Net Core)編寫。IIS更改WebApi連接字符串

在早期的網絡應用程序中,可以更改windows-Explorer中的web.config中的連接字符串,並且運行在IIS上的網站使用web.config文件中的ConnectionString。

這仍然是可能的現代WebAPI(我有ConnectionString insite appsettings.json)?我沒有找到IIS或File-Explorer內部的解決方案,並且使用Environment-Variables不符合我們的需求。

我們需要在多個DB實例之間切換,因此非常歡迎非常輕量級的基於文件的解決方案。我們正在使用EntityFrameworkCore(又名EF7)數據庫 - 首先,因爲它是一個新的工具,它是我們當前的數據庫之上。

回答

0

您可以使用其中一個配置源(包括JSON,通過包Microsoft.Extensions.Configuration.Json中的AddJsonFile()訪問)讀取設置文件,然後使用從此處讀取的值配置EF。

示例代碼看起來是這樣的:

public Startup(IHostingEnvironment env) 
{ 
    var builder = new ConfigurationBuilder() 
     .SetBasePath(env.ContentRootPath) 
     .AddJsonFile("appsettings.json"); 

    Configuration = builder.Build(); 
} 

public IConfigurationRoot Configuration { get; } 

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddDbContext<MyDbContext>(options => 
     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 
} 

欲瞭解更多信息,請參閱Configuration in ASP.NET Core docsthis answer

+0

謝謝svick!配置'options.UseSqlServer(Configuration [「Data:DefaultConnection:ConnectionString」])'做了竅門。我只需在更改ConnectionString後重新啓動IIS應用程序(或池),但這對我們的測試環境來說可能會更好,因爲我們不會經常更改它:-) – nicn