net core 2 读取appsettings.json

问:
.Net Core: Application startup exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
 
答:
问题代码:
public Startup()
{
var builder = new ConfigurationBuilder().AddJsonFile("AppSetting.json");
Configuration = builder.Build();
}
 
 
正确代码:
public Startup(IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder().SetBasePath(environment.ContentRootPath).AddJsonFile("AppSetting.json");
Configuration = builder.Build();
}
原文:https://www.cnblogs.com/icebutterfly/p/6797099.html
问题没有解决,只好搜索继续
找到https://www.cnblogs.com/OpenCoder/p/9761067.html

static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

IConfigurationRoot configuration = builder.Build();

Console.WriteLine(configuration.GetConnectionString("Storage"));
Console.WriteLine(configuration.GetSection("ConnectionStrings:Storage").Value);
}

 

自己webapi程序不从Startup.cs读取,验证后修改如下
        protected static IConfiguration Configuration { get; set; }
        protected static string connection { get; set; }
        static DataManager()
        {
            string ss = AppContext.BaseDirectory;
            string aa = Directory.GetCurrentDirectory();       
            var builder = new ConfigurationBuilder()
                     .SetBasePath(AppContext.BaseDirectory)
                     .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
            Configuration = builder.Build();
            connection = Configuration.GetConnectionString("DefaultConnection");
        }

posted @ 2019-05-15 14:02  没有想到好名字  阅读(972)  评论(0编辑  收藏  举报