我是 Asp.Net Core 和 EF 的新手。我正在從資料庫端開發一個簡單的 CRUD,使用該Secrets.json檔案隱藏我的連接字串憑據。
但我不知道如何使用 AddDbContext() 參考檔案。
到目前為止我的代碼:
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();
}
當代碼運行時,我得到這個錯誤就AddDbContext<>行了
System.ArgumentNullException HResult=0x80004003 訊息=值不能為空。(引數'connectionString')
Source=Microsoft.EntityFrameworkCore.SqlServer StackTrace: etc etc
我認為這是因為代碼正在檔案中尋找引數,我不希望連接字串出現在該appsettings.json檔案中。
我錯過了什么?
uj5u.com熱心網友回復:
在 ASP.NET 6 之前:
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; }
//...
}
或者在 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>();
});
在 ASP.NET 6 中:
您可以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:
{
"ConnectionStrings": {
"myConxStr": "xxxxxxx"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/444888.html
