gpt4 book ai didi

asp.net-core - ASP.NET Core 2.x OnConfiguring 从 appsettings.json 获取连接字符串

转载 作者:行者123 更新时间:2023-12-03 23:14:51 25 4
gpt4 key购买 nike

刚刚开始使用 ASP.NET Core,到目前为止令人印象深刻。在生成的代码中,(见下文)。我想更改硬编码的连接字符串以从 appsettings.json 中获取它文件。

这显然是不可能的。我还没有找到一个有效的示例(甚至构建)。

这是怎么回事??
请帮忙

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=xxxxxxx;Database=xxxxx;Trusted_Connection=True;");
}
}

提供的链接在一个区域解决了问题,但在 OnConfiguring 中不起作用.我究竟做错了什么 ?
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

var connection = Configuration.GetConnectionString("ConnectionName");
services.AddDbContext<SurveyContext>(options => options.UseSqlServer(connection));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}

最佳答案

在 .NET Core 项目的启动类中,您通常会在 ConfigureServices 函数中注册它。

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourContext>(options => options.UseSqlServer(connection));
}

当您在 .NET Core 的启动类中时,从 appsettings.json 读取值是没有问题的。

您可以在 Microsoft 阅读更多内容,即: https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db

关于asp.net-core - ASP.NET Core 2.x OnConfiguring 从 appsettings.json 获取连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53071902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com