[英]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 etcSource=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 的基本步骤(参考上面的链接):
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 用户机密初始化
Create the new secret:创建新秘密:
dotnet user-secrets set "MyDbPassword" "SuperSecretPassword123" dotnet 用户机密集“MyDbPassword”“SuperSecretPassword123”
A secrets.json file is created:创建一个 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.