Read connection from appsettings.json in .net core 1.1 web api

亡梦爱人 提交于 2019-12-24 10:13:32

问题


I am create a web api project in .net core 1.1 but problem is when its try to read connectionstring from appsettings.json an exception occurs .

System.IO.FileNotFoundException: 'The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\Test\netCoreWebApi\netCoreWebApi\bin\Debug\netcoreapp1.1\appsettings.json'.'

Startup.cs

public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<NorthWindDBContext>();
            // Add framework services.
            services.AddMvc();

            services.AddScoped<ICategory_Product, Category_ProductRepository>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc();
        }
    }

also eclare connectionstring in DBContext class (may be I am doing wrong here)

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var builder = new ConfigurationBuilder()
                       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

            var configuration = builder.Build();

            string connectionString = configuration.GetConnectionString("northwindConnection");
            optionsBuilder.UseMySql(connectionString);


        }

so wats the correct way .

please help .

来源:https://stackoverflow.com/questions/44163312/read-connection-from-appsettings-json-in-net-core-1-1-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!