问题
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