相关疑难解决方法(0)

从appsettings.json获取ConnectionString,而不是在.NET Core 2.0 App中进行硬编码

我在NET Core2.0 App中有以下类.

// required when local database does not exist or was deleted
public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext>
{
    public AppContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<AppContext>();
        builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new AppContext(builder.Options);
    }
}
Run Code Online (Sandbox Code Playgroud)

当Database不存在时,在Core 2.0中需要进行迁移,并且必须在运行update-database时创建.
升级到ASP.NET Core 2.0后无法创建迁移

我想在2个地方(这里和appsettings.json)没有ConnectionString,但只在.json,所以我试图更换

"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"
Run Code Online (Sandbox Code Playgroud)

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我得到空值.

更新1:
请注意,在Core 2中明确添加.json是不必要的,所以问题不在于文件.
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/

更新2:
此外,我已经使用Configuration从.json向Context发送ConnectionString:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); …
Run Code Online (Sandbox Code Playgroud)

connection-string appsettings asp.net-core

43
推荐指数
6
解决办法
10万
查看次数

如何确保将appsettings.dev.json复制到输出文件夹?

我有三个配置文件,每个环境一个:

  1. appsettings.json - >制作
  2. appsettings.dev.json - >开发
  3. appsettings.stg.json - > staging

如果我将ASPNETCORE_ENVIRONMENT设置为dev,我会收到一个运行时异常,抱怨无法找到appsettings.dev.json.我尝试添加

"copyToOutput": [
  "appsettings.dev.json"
]
Run Code Online (Sandbox Code Playgroud)

buildOptionsproject.json中的部分,但它似乎没有任何影响.

有没有其他方法可以强制appsettings.dev.json被复制到输出目录?

c# asp.net configuration web-deployment asp.net-core

14
推荐指数
5
解决办法
1万
查看次数