简体   繁体   English

如何从 Asp.Net Core 6 中的 Secrets.json 获取 ConnectionString?

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

I am new to Asp.Net Core and EF.我是 Asp.Net Core 和 EF 的新手。 I am developing a simple CRUD from database-end, using the Secrets.json file to hide my connection string credentials.我正在从数据库端开发一个简单的 CRUD,使用Secrets.json文件隐藏我的连接字符串凭据。

But I don't know how to reference the file using AddDbContext().但我不知道如何使用 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代码运行时,我在AddDbContext<>行上收到此错误

System.ArgumentNullException HResult=0x80004003 Message=Value cannot be null. System.ArgumentNullException HResult=0x80004003 消息=值不能为空。 (Parameter 'connectionString') (参数“连接字符串”)
Source=Microsoft.EntityFrameworkCore.SqlServer StackTrace: etc etc Source=Microsoft.EntityFrameworkCore.SqlServer StackTrace: 等等

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.我认为这是因为代码正在appsettings.json文件中查找参数,而我不希望连接字符串出现在该文件中。

What am I missing?我错过了什么?

Before ASP.NET 6 :在 ASP.NET 6 之前

You can adding additional Secrets.json file to configuration argument in Startup.cs like below:您可以将额外Secrets.json文件添加到Startup.cs中的配置参数,如下所示:

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:或者在 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 :在 ASP.NET 6 中

You can add it in Program.cs like below:您可以在Program.cs中添加它,如下所示:

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 :然后确保您的json 文件( Secrets.json )必须如下所示

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

In the MS documentation there is a full walk through for app secrets .在 MS 文档中,有一个完整的应用程序机密演练 Of note, even MS suggests this is for non-production use.值得注意的是,甚至 MS 也建议这是用于非生产用途。 If you need Startup.cs, the top left there is a dropdown to select v5 or earlier.如果您需要 Startup.cs,左上角有一个下拉菜单可以选择 v5 或更早版本。

Basic Steps for ASP.NET Core 6.0 (refer to link above): ASP.NET Core 6.0 的基本步骤(参考上面的链接):

  1. Initialize the secrets within the project directory via cli, a 'UserSecretsId' will be created in the PropertyGroup in the projectName.csproj file:通过 cli 初始化项目目录中的 secret,将在 projectName.csproj 文件的 PropertyGroup 中创建一个“UserSecretsId”:

    dotnet user-secrets init dotnet 用户机密初始化

  2. Create the new secret:创建新秘密:

    dotnet user-secrets set "MyDbPassword" "SuperSecretPassword123" dotnet 用户机密集“MyDbPassword”“SuperSecretPassword123”

  3. A secrets.json file is created:创建一个 secrets.json 文件:

    • Windows: %APPDATA%\Microsoft\UserSecrets<user_secrets_id>\secrets.json Windows:%APPDATA%\Microsoft\UserSecrets<user_secrets_id>\secrets.json
    • Mac/Linux: ~/.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'要在您的情况下在 Program.cs 中使用 ConnectionStrings,请在文档中向下滚动到“用秘密替换字符串”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 asp.net 核心 web Z8A5DA52ED1206447A8AAZE7 获取 JSON 阵列作为响应 - How to get the JSON array as respone from asp.net core web api ASP.NET实体框架7 config.json ConnectionString - ASP.NET Entity Framework 7 config.json ConnectionString ASP.NET Core中关于GET请求的不完整JSON数据 - Incomplete JSON data on GET request in ASP.NET Core 如何从项目根目录获取 appsettings 到 ASP.NET Core 2.0 和 EF Core 2.0 中的 IDesignTimeDbContextFactory 实现 - How to get appsettings from project root to IDesignTimeDbContextFactory implementation in ASP.NET Core 2.0 and EF Core 2.0 ASP.NET MVC数据库ConnectionString说明 - ASP.NET MVC Database ConnectionString Explanation ASP.NET连接字符串不符合规范 - ASP.NET connectionstring does not conform to specification ConnectionString属性还没有初始化执行第二次 asp.net core - The ConnectionString property has not been initialized executing for second time asp.net core 从ASP.NET Core中的MySQL服务器获取数据 - Get data from MySQL server in ASP.NET Core 如何从EF Core 2.0 DbContext获取connectionString - How to get connectionString from EF Core 2.0 DbContext asp.net core 如何从数据库中按降序获取数据 - How to get data in descending order from database in asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM