C# 从.net core 1.1 web api中的appsettings.json读取连接
我正在.net core 1.1中创建一个web api项目,但问题是当它尝试从appsettings.json读取connectionstring时,会发生异常 System.IO.FileNotFoundException:'配置文件 找不到“appsettings.json”,它不是可选的。身体 路径是 'C:\Test\netCoreWebApi\netCoreWebApi\bin\Debug\netcoreapp1.1\appsettings.json' Startup.csC# 从.net core 1.1 web api中的appsettings.json读取连接,c#,asp.net-web-api,database-connection,.net-core,C#,Asp.net Web Api,Database Connection,.net Core,我正在.net core 1.1中创建一个web api项目,但问题是当它尝试从appsettings.json读取connectionstring时,会发生异常 System.IO.FileNotFoundException:'配置文件 找不到“appsettings.json”,它不是可选的。身体 路径是 'C:\Test\netCoreWebApi\netCoreWebApi\bin\Debug\netcoreapp1.1\appsettings.json' Startup.cs publ
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();
}
}
所以这是正确的方法
请提供帮助。物理路径上是否有
appsettings.json
可用?您使用的是-VS2015(project.json)还是VS2017(csproj)?应该将文件appsettings.json
添加到您的应用程序入口点,如果在web项目中使用,它应该具有Build action:Content
属性。如果问题尚未解决,请尝试设置Copy to output directory:Always
属性。@Sanket VS2017(csproj)。正如Ilya Chumakov所述,在appsetting.json属性中,将Copy Always设置为Copy to output directory属性。我认为,在完成之前的设置后,与appsettings.json相关的问题已得到解决。现在,您正面临与EFcore相关的错误。appsettings.json
在物理路径上可用吗?您使用的是-VS2015(project.json)还是VS2017(csproj)?应该将文件appsettings.json
添加到您的应用程序入口点,如果在web项目中使用,它应该具有Build action:Content
属性。如果问题尚未解决,请尝试设置Copy to output directory:Always
属性。@Sanket VS2017(csproj)。正如Ilya Chumakov所述,在appsetting.json属性中,将Copy Always设置为Copy to output directory属性。我认为,在完成之前的设置后,与appsettings.json相关的问题已得到解决。现在,您将面临与EFcore相关的错误。
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);
}