asp.net-core-webapiconnection-string

builder.Configuration.GetConnectionString("DefaultConnection") Returns Null


I have an ASP.NET Core 6 Web API project. My controller will connect to a SQL Server database. When I run the app I can't get the connection string in Program.cs, it's returned as null.

Here's my Program.cs:

using Marois.Framework.AppSecurity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// ==== This line returns NULL
var connString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<AppSecurityDataContext>(options =>
    options.UseSqlServer(connString));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Both AppSettings.json and AppSettings.Development.json files have this in them:

{
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=MAROIS_KEVIN_2\\SQLEXPRESS;Database=Falcon;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
      "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
      }
    }
  }
}

Any idea why this isn't working?


Solution

  • For the call to .GetConnectionString() to work, you need to have a JSON section ConnectionStrings like this - at the top level of your app settings:

    {
       "ConnectionStrings": {
            "DefaultConnection": "Server=MAROIS_KEVIN_2\\SQLEXPRESS;Database=Falcon;Trusted_Connection=True;MultipleActiveResultSets=true"
       },
       // .....
       "Logging": {
           // ....
       }
    }
    

    Your current settings is under a Data node - which is wrong