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

前端之家收集整理的这篇文章主要介绍了asp.net-core – 从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);
    }
}

当Database不存在时,在Core 2.0中需要进行迁移,并且必须在运行update-database时创建。
Unable to create migrations after upgrading to ASP.NET Core 2.0

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

"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true"

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString

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

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

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

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")));
    }
}

但我不能将它用于ToDoContextFactory,因为它没有配置,并且迁移使用ToDoContextFactory,因此App根本不运行。

解:
根据@JRB的答案,我让它的工作方式如下:

public AppContext CreateDbContext(string[] args)
{
    string projectPath = AppDomain.CurrentDomain.BaseDirectory.Split(new String[] { @"bin\" },StringSplitOptions.None)[0];
    IConfigurationRoot configuration = new ConfigurationBuilder()
        .SetBasePath(projectPath)
        .AddJsonFile("appsettings.json")
        .Build();
    string connectionString = configuration.GetConnectionString("DefaultConnection");

    var builder = new DbContextOptionsBuilder<AppContext>();
    builder.UsesqlServer(connectionString);

    return new AppContext(builder.Options);
}

解决方法

第1步:在OnConfiguring()中包含以下内容
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UsesqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

第2步:创建appsettings.json:

{
    "ConnectionStrings": {       
      "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
    } 
  }

第3步:将appsettings.json硬拷贝到正确的目录

Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory. 
  Use your debugger to find out which directory that is.

假设:您已经在项目中包含了Microsoft.Extensions.Configuration.Json(从Nuget获取)包。

原文链接:https://www.f2er.com/netcore/252035.html

猜你在找的.NET Core相关文章