我试图在我的appsettings.json文件中写入连接字符串,并将其带入我的启动文件中,但我一直在获取Value不能为null。参数名称:connectionString。
添加迁移时,程序包管理器控制台中出现以下错误。
这是我的创业公司:
namespace WebApi
{
public class Startup
{
private string _connectionString = null;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
_connectionString = Configuration["secretConnectionString"];
services.AddMvc();
services.AddEntityFrameworkNpgsql().AddDbContext<ApiContext>
(Options => Options.UseNpgsql(_connectionString));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
appsettings.json:
"connectionString": {
"_connectionString": " User Id=Pdev; Password=abcd;Server=localhost;Port=5432;Database=Advantage.Api.Dev;Integrated Security=true;Pooling=true;"
},
最佳答案
代替
_connectionString = Configuration["secretConnectionString"];
尝试使用_connectionString = Configuration.GetValue<string>(
"connectionString:_connectionString")