【问题标题】:DB Connection problem "Value cannot be null. (Parameter 'connectionString')" (Identity ASP.NET)数据库连接问题“值不能为空。(参数'connectionString')”(Identity ASP.NET)
【发布时间】:2020-08-08 16:34:04
【问题描述】:

我正在尝试与托管在 Azure 上的数据库建立连接,但我在代码中遇到了一些问题,当我运行应用程序时,它会导致参数中出现错误:connectionString。

STARTUP.CS

{
public class Startup
{
    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)
    {

        services.AddDbContext<Contexto>
        (
            options => options.UseSqlServer("Data Source=Exemple.database.windows.net;Initial Catalog=NameDataDB;Persist Security Info=True;User ID=UserDB;Password=***********")
        );
        services.AddDbContext<IdentityContexto>
        (
            options => options.UseSqlServer("Data Source=exemple.database.windows.net;Initial Catalog=NameUserDB;Persist Security Info=True;User ID=userdb;Password=***********")
        );

CONTEXTO.CS

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("NameDB"));
        base.OnConfiguring(optionsBuilder);
    }
}

当我运行应用程序时出现以下错误:

ArgumentNullException: Value cannot be null. (Parameter 'connectionString')

【问题讨论】:

  • configuration.GetConnectionString("NameDB")) - 这是问题所在,我想是因为使用此代码,您说 ASP.NET Core 查看 appsettings.json 和其他包含的 json 文件并找到 'NameDB ' 参数。
  • this configuration.GetConnectionString("NameDB") 为空,显示你的 appsettings.json,你应该有一个像这样的部分 "ConnectionStrings": { "NameDB": " " },
  • 如果解决了您的问题,请标记答案。

标签: asp.net asp.net-identity asp.net-core-webapi webapi


【解决方案1】:

configuration.GetConnectionString 不会得到你的连接字符串,除非你像这样在 appSettings 中添加它们:

{ "连接字符串": { "BloggingDatabase": "服务器=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;" }, }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 2016-04-07
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多