Home > Enterprise >  NullReferenceException when adding Identity in .NET Core project
NullReferenceException when adding Identity in .NET Core project

Time:03-16

I have a ASP.NET Core 6 webapp that uses EF Core for its database management and ASP.NET Identity functionality to manage users. This webapp works without issues.

Now, I wanted to develop a standalone console application that is used to perform maintenance tasks on the Database (seeding, cleanup operations, factory reset, etc.)

However I'm running into a problem. I've added to the maintenance app's initialization steps the same instructions I use on the webapp to configure EF Core and Itentity, which are very simple:

private static IHost CreateHost(string[] args)
{
    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureServices((_, services) =>
        {
            services.AddDbContext<MyContext>(options =>
            {
                options.UseSqlite(connectionString);
            });

            services.AddDefaultIdentity<MyUser>(opt => { });
            services.AddScoped<MyDbService>();
        });
    return builder.Build();
}

however, while these instructions work correctly in my webapp, in the console app they don't. In particular, I get a NullReferenceException when invoking services.AddDefaultIdentity<MyUser>(opt => { });

There is no inner exception or other info in the message. The stack trace is like this:

   at Microsoft.AspNetCore.Identity.IdentityBuilderUIExtensions.GetApplicationAssembly(IdentityBuilder builder)
   at Microsoft.AspNetCore.Identity.IdentityBuilderUIExtensions.<>c__DisplayClass0_0.<AddDefaultUI>b__0(ApplicationPartManager apm)
   at Microsoft.Extensions.DependencyInjection.MvcCoreMvcBuilderExtensions.ConfigureApplicationPartManager(IMvcBuilder builder, Action`1 setupAction)
   at Microsoft.AspNetCore.Identity.IdentityBuilderUIExtensions.AddDefaultUI(IdentityBuilder builder)
   at Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionUIExtensions.AddDefaultIdentity[TUser](IServiceCollection services, Action`1 configureOptions)
   at MainetnanceApp.Program.<>c.<CreateHost>b__2_0(HostBuilderContext _, IServiceCollection services)

Why is this happening? Does it have something to do with the fact that it is a console app rather than a webapp? How can I fix this?

CodePudding user response:

AddDefaultIdentity is meant for a web app and not a console App. It adds UI, token providers, and configures authentication to use identity cookies.

For console apps, you can use AddIdentityCore instead.

  • Related