简体   繁体   中英

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?

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"
  }
}

In the MS documentation there is a full walk through for app secrets . Of note, even MS suggests this is for non-production use. If you need Startup.cs, the top left there is a dropdown to select v5 or earlier.

Basic Steps for ASP.NET Core 6.0 (refer to link above):

  1. Initialize the secrets within the project directory via cli, a 'UserSecretsId' will be created in the PropertyGroup in the projectName.csproj file:

    dotnet user-secrets init

  2. Create the new secret:

    dotnet user-secrets set "MyDbPassword" "SuperSecretPassword123"

  3. A secrets.json file is created:

    • Windows: %APPDATA%\Microsoft\UserSecrets<user_secrets_id>\secrets.json
    • Mac/Linux: ~/.microsoft/usersecrets/<user_secrets_id>/secrets.json

To use in Program.cs in your case for the ConnectionStrings, scroll down in the documentation to 'String replacement with secrets'

var conStrBuilder = new SqlConnectionStringBuilder(
    builder.Configuration.GetConnectionString("MyDbConnectionWithoutPassword"));
conStrBuilder.Password = builder.Configuration["MyDbPassword"];
var connection = conStrBuilder.ConnectionString;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM