2017-08-24 67 views
0

我目前在.net核心2.0中創建了一個Web Api,我簡直不能讓我的連接字符串工作。.Net Core無法從appsettings.json讀取連接字符串

我已經把我的ConnectionString到appsettings.json和startup.cs

加載Appsettings.json

{ 
"Logging": { 
"IncludeScopes": false, 
"Debug": { 
    "LogLevel": { 
    "Default": "Warning" 
    } 
}, 
"Console": { 
    "LogLevel": { 
    "Default": "Warning" 
    } 
}, 
"ConnectionStrings": { 
    "DatabaseConnection": "Data Source=VMDEVSLN-EOE\\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True" 
    } 
} 
} 

Startup.cs

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

    public IConfiguration Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddMvc(); 
     var connection = Configuration.GetConnectionString("DatabaseConnection"); 
     services.AddDbContext<DatabaseContext>(options => options.UseSqlServer(connection)); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 

     app.UseMvc(); 
    } 
} 

的DbContext

public class DatabaseContext : DbContext 
{ 
    public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) 
    { 

    } 
    public DbSet<CustomerTB> CustomerTB { get; set; } 
} 

我相信問題存在於我的appsettings.json某處,但我只是找不到它

+1

如果你改變'Configuration.GetConnectionString( 「的DatabaseConnection」)什麼;'到 '配置[ 「的ConnectionStrings:的DatabaseConnection」]' – Brivvirs

+0

小號直到相同的錯誤。沒有解決它:( – Ekos

+0

如果連接字符串是從appSettings? – Brivvirs

回答

10

ConnectionStrings部分是Logging段內,我不知道這是你的意思,但無論如何你可以訪問在DatabaseConnection這樣的:

var connection = Configuration["Logging:ConnectionStrings:DatabaseConnection"]; 
+0

這是一個很棒的地方。 –

+0

謝謝,花了我幾分鐘的時間纔想出來的。 – anserk

+1

@KirkLarkin:從技術上說,「Logging:ConnectionStrings:DatabaseConnection」沒有錯,但ConnectionStrings應該是Logging的兄弟,而不是它的子級,以便您可以使用ConnectionStrings訪問它: DatabaseConnection。 –

0

在asp.net核心1.x中,您應該通過ConfigurationBuilder讀取設置。在Startup.cs

public Startup(IHostingEnvironment env) 
{ 
    var builder = new ConfigurationBuilder() 
     .SetBasePath(env.ContentRootPath) 
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) 
     .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
     .AddEnvironmentVariables(); 
    Configuration = builder.Build(); 
} 

這可能是在asp.net核心相同的方法2.

+0

這沒有解決問題:( – Ekos