Search code examples
entity-frameworkasp.net-coreconnection-stringsecretsmanager

How to get ConnectionString from Secrets.json in Asp.Net Core 6?


I am new to Asp.Net Core and EF. I am developing a simple CRUD from database-end, using the Secrets.json file to hide my connection string credentials.

But I don't know how to reference the file using AddDbContext().

My code so far:

 public class Startup
    {
        public Startup(IConfigurationRoot configuration)
        {
            Configuration = configuration;
        }
        public IConfigurationRoot Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddDbContext<POTS.myDBContext>(options => 
                options.UseSqlServer(Configuration.GetConnectionString("myConxStr")));
            services.AddControllers();
        }

When the code runs, I get this error on the AddDbContext<> line

System.ArgumentNullException HResult=0x80004003 Message=Value cannot be null. (Parameter 'connectionString')
Source=Microsoft.EntityFrameworkCore.SqlServer StackTrace: etc etc

I think this is because the code is looking for the parameter in the appsettings.json file, where I don't want the connectionstring to be.

What am I missing?


Solution

  • Before ASP.NET 6:

    You can adding additional Secrets.json file to configuration argument in Startup.cs like below:

    public class Startup
    {
        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            configuration = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
            .AddJsonFile("Secrets.json")
            .Build();
    
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
        //...
    }
    

    Or add it in Program.cs:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;
    
            config.SetBasePath(env.ContentRootPath)
                .AddJsonFile("Secrets.json", optional: true, reloadOnChange: true);
    
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });
    

    In ASP.NET 6:

    You can add it in Program.cs like below:

    var builder = WebApplication.CreateBuilder(args);
    builder.Configuration
        .SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("Secrets.json");
    
    builder.Services.AddDbContext<POTS.myDBContext>(options =>
            options.UseSqlServer(builder.Configuration.GetConnectionString("myConxStr")));
    
    // Add services to the container....
    var app = builder.Build();
    //....
    

    Then be sure your json file(Secrets.json) must be like below:

    {
      "ConnectionStrings": {
        "myConxStr": "xxxxxxx"
      }
    }