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

标签 asp.net-core visual-studio-2017

刚刚开始使用 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/

相关文章:

c# - 如何在ConfigureServices方法中获取IOptions?

asp.net-core - .NET 核心自定义和默认绑定(bind)相结合

visual-studio - Visual Studio 安装项目 - 如何避免重复条目?

.net - Visual Studio 2017 引用管理器为空

ios - 如何使用 visual studio 2017 在 mac 上更新 xamarin.ios?

visual-studio - 在 Visual Studio 任务列表中隐藏 TODO 标签

asp.net - 如何将值传递给部分标签助手? (ASP.NET 核心)

c# - StreamReader.ReadLine() 不消耗流

c++ - 没有花括号的枚举形式

performance - Kestrel 服务器与 HTTP.sys