繁体   English   中英

将连接字符串传递给 .net-core 3 MVC 中的其他项目

[英]Passing Connection string to other projects in .net-core 3 MVC

我最近从 .net-core 和 MVC 开始,所以我从一个初学者问题开始。

我创建了新项目“Project.web”并添加到同一个解决方案库项目“Project.data”中。 现在我想将数据库连接字符串传递给 Project.data,所以我在 Startup.cs 中编写了这段代码:

public void ConfigureServices(IServiceCollection services)
    {
        var cc
            = Configuration.GetConnectionString("ConnString");
        services.AddDbContext<muniCVContext>(options =>
            options.UseNpgsql(cc));
        services.AddControllersWithViews();


    }

我引用了 Project.data.Models 命名空间,但它不会传递该连接字符串。

在 Project.data 库中创建 examplesetting.json(您可以使用自定义 setting.json)文件。

示例设置.json

{
  "ConnectionStrings": {
    "ConnString": "YOUR_CONNECTION_STRING"
  }
}

不要忘记设置 examplesetting.json 属性。
Select Copy to Output DirectoryCopy always并重建您的项目(Ctrl + Shift + B)。

在此处输入图像描述

将配置更改为您的自定义配置并使用它。

public void ConfigureServices(IServiceCollection services)
{
    // create configuration by examplesetting.json
    var builder = new ConfigurationBuilder();
    builder.AddJsonFile("examplesetting.json");
    var configuration = builder.Build();
    
    // use examplesetting configuration to get the ConnString
    var cc = configuration.GetConnectionString("ConnString");
    services.AddDbContext<muniCVContext>(options => options.UseNpgsql(cc));
    services.AddControllersWithViews();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM