IIS 更改 WebApi ConnectionString

IIS Change WebApi ConnectionString

我们正在将 webApi 用于我们最新的产品之一,该产品托管在 IIS7.5 上并用 ASP.NET5 (.Net Core) 编写。

在早期的网络应用程序中,可以在 windows-Explorer 中更改 web.config 中的连接字符串,并且 IIS 上的网站 运行 使用 [=10] 中的 ConnectionString =] 文件.

这对于现代 WebAPI 是否仍然可行(我在站点 appsettings.json 中有 ConnectionString)?我没有在 IIS 或 File-Explorer 中找到解决方案,使用环境变量不符合我们的需求。

我们需要在多个数据库实例之间切换,因此非常欢迎基于文件的非常轻量级的解决方案。

PS:我们正在使用 EntityFrameworkCore(又名 EF7)数据库优先,因为它是我们当前数据库之上的一个新工具。

您可以使用其中一个配置源(包括 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 docs or