在主要功能中找不到appsettings.json文件?

时间:2020-04-05 06:35:41

标签: c# .net .net-core

我正在尝试从Main方法访问appsettings.json并传递给DBContext以获取连接字符串。但是出现Configuration = builder.Build();错误。有什么其他方法可以尝试获取连接字符串吗?

System.IO.FileNotFoundException: 'The configuration file 'appsettings.json' was not found and is not optional.  
The physical path is 'C:\Trunk\Repos\ZiplinePackage\bin\Debug\netcoreapp3.1\appsettings.json'.'

Program.cs

class Program
{
    public static IConfigurationRoot Configuration { get; set; }
    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();
        var context = new DataContext(Configuration);
        var speCommonData = context.SpeCommonData.Where(s => s.Status == "NLM GENERATED").ToList();
    }
}

enter image description here

DataContext.CS 文件

public class DataContext : DbContext
{

    public DataContext(IConfiguration configuration)
    {
        configuration = configuration;
    }
    public DataContext(DbContextOptions<DataContext> options)
        : base(options)
    {
    }
    private string _connectionString;
    public static IConfigurationRoot configuration;

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
           optionsBuilder.UseSqlServer(configuration.GetConnectionString("MISCDBConnection"));
        }

    }

2 个答案:

答案 0 :(得分:1)

删除while(!fin.eof())方法

!fin.eof()

或这样设置基本路径

SetBasePath

答案 1 :(得分:1)

您的应用程序在运行时找不到文件。这意味着该文件未包含在构建中。确保 <RoundButton@Button>: background_color: 0,0,0,0 canvas.before: Color: rgba: (.7,.7,.7,0.7) if self.state=='normal' else (0.5,1,1,1) RoundedRectangle: pos: self.pos size: self.size radius: [10,] <MyTextInput@TextInput>: background_normal: "textinput.png" background_color: (0.82,0.96,0.92,1) if self.focus else (1,1,1,0.5) <MyGrid>: txt:txt words:words FloatLayout: size: root.width, root.height MyTextInput: id: txt pos_hint: {"x":0.05, "top":0.8} size_hint: 0.63,0.75 MyTextInput: id: words on_text: root.find_words() pos_hint: {"x": 0.7, "top":0.8} size_hint: 0.25,0.75 text:"hello" RoundButton: text:"Submit" on_press: root.btn() pos_hint: {"x":0.05, "top":0.95} size_hint: 0.2,0.1 具有以下属性:

  • 构建操作=内容
  • 复制到输出目录=如果较新则复制

enter image description here