【发布时间】:2022-11-16 21:07:53
【问题描述】:
在旧版本的 ASP.Net Core 中,你有 startup.cs 文件,你可以在其中做很多工作,包括读取和设置应用程序环境,然后基于它你可以读取不同版本的 appsettings.json 文件。在新的 ASP.Net Core 7 中,他们摆脱了 Startup.cs 并大大简化了 program.cs 文件。现在我不知道如何读取环境,然后将 Entity Framework 7 传递给我的连接字符串。环顾四周,我发现不适用于版本 7 的所有答案或告诉您通过重新制作整个 Startup.cs 文件来撤消版本 7 中的所有工作。我们应该如何根据 .Net 7 中的环境注入连接字符串?
我确实有代码可以从基本的 appsettings.json 文件中读取并且可以正常工作,还有一个部分可以读取环境,但是它是在 DbContext 注入之后进行设置的。这是我的 program.cs 文件,我只是迷失了需要更新的内容。我查看了 Microsoft 文档,但没有看到任何适用于环境和字符串注入的内容。
var builder = WebApplication.CreateBuilder(args);
//Add Services (builder.Services.AddScoped<IService, Service>();
builder.Services.AddScoped<INavigationHelper, NavigationHelper>();
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
builder.Services.AddRazorPages().AddMicrosoftIdentityUI();
builder.Services.AddDbContext<SiteDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Database")));
var app = builder.Build();
if (!app.Environment.IsDevelopment()) { app.UseHsts(); }
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();
应用设置.json:
{
"AzureAd":
{
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "",
"ClientId": "",
"CallbackPath": "",
"ClientSecret": "Client secret from app-registration. Check user secrets/azure portal.",
"ClientCertificates":
[
]
},
"Logging":
{
"LogLevel":
{
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings":
{
"Database": ""
}
}
appsettings.development.json
{
"Logging":
{
"LogLevel":
{
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
},
"ConnectionStrings":
{
"Database": ""
}
}
}
【问题讨论】:
标签: c# asp.net-core entity-framework-core asp.net-core-7.0 ef-core-7.0