简体   繁体   中英

{"Value cannot be null. (Parameter 'connectionString')"} System.ArgumentNullException in Blazor Webassembly project

In my project, the connectionString throws a null pointer exception in runtime, even though it is configured correctly. 空指针错误截图

appsettings.json

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-<DATABASE_NAME>;Trusted_Connection=True;MultipleActiveResultSets=true",
    "CustomConnection": "Server=(localdb)\\mssqllocaldb;Database=<DATABASE_NAME>"
  }

Startup.cs

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

What could I be missing here? Thanks in advance.

ApplicationDbContext.cs

using IdentityServer4.EntityFramework.Options;
using Microsoft.AspNetCore.ApiAuthorization.IdentityServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using App.Models;
using App.Shared;

namespace App.Server.Data
{
    public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>
    {
        public ApplicationDbContext(
            DbContextOptions options,
            IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
        {

        }
        
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.ApplyConfiguration(new RoleConfiguration());
        }
    }

}

Instead of using the AddDbContext extension method provided by EntityFrameworkCore, which expects a standard constructor on the DbContext, use AddScoped directly and provided a method that returns the constructed DbContext using the custom parameters:

Change:

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

To:

IOptions<OperationalStoreOptions> osOptions;

services.AddScoped<ApplicationDbContext>(sp =>
{
    DbContextOptionsBuilder<ApplicationDbContext> optsBuilder =
        new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection");

    // If an instance of osOptions is available at this time
    return new ApplicationDbContext(optsBuilder.Options, osOptions);    

    // Or, if the options are registered in the service container
    // then resolve from the service provider
    return new ApplicationDbContext(
        optsBuilder.Options, 
        sp.GetRequiredService<IOptions<OperationalStoreOptions>());

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM