Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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

like image 910
Ekos Avatar asked Sep 19 '26 19:09

Ekos


1 Answers

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"];
like image 80
anserk Avatar answered Sep 21 '26 08:09

anserk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!