我在.net核心1.1中创建了一个web api项目,但问题是当它尝试从appsettings.json读取connectionstring时发生异常。
System.IO.FileNotFoundException:'配置文件 'appsettings.json'找不到,也不是可选的。身体上的 路径是 'C:\测试\ netCoreWebApi \ netCoreWebApi \ BIN \调试\ 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();
}
}
也是DBContext类中的eclare connectionstring(可能我在这里做错了)
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);
}
所以这是正确的方式。
请帮忙。