Ekos
Ekos

Reputation: 725

.Net Core Cant read connection string from appsettings.json

I'm currently creating a Web Api in .net core 2.0 and I simply cant get my connection string to work.

I've put my connectionstring into appsettings.json and load it in 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; }
}

I believe the problem lies somewhere in my appsettings.json but I just cant find it

Upvotes: 2

Views: 14218

Answers (2)

anserk
anserk

Reputation: 1320

Your ConnectionStrings section is inside the Logging section, I don't know if that's what you meant but anyway you can access the DatabaseConnection like this:

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

Upvotes: 13

Ivan R.
Ivan R.

Reputation: 1915

In asp.net core 1.x you should read settings through ConfigurationBuilder. In 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();
}

It could be the same approach in asp.net core 2.

Upvotes: 0

Related Questions