locked
IServiceCollection does not contain a definition for AddDefaultIdentity RRS feed

  • Question

  • User1428199325 posted

    Any idea why am I getting this error?   Error Message --> "IServiceCollection does not contain a definition for AddDefaultIdentity"

    I'm using .NET Core v3.1 as per migration from v1.1

    public class Program
    {
      public async static void Main(string[] args)
      {
        await Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => {
          webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
          webBuilder.UseKestrel();
          webBuilder.UseAzureAppServices();
          webBuilder.UseStartup<Startup>();
        })
        .Build()
        .RunAsync();
      }
    }

    public class Startup

        {

            public Startup(IConfiguration configuration, IHostEnvironment hostEnvironment)

            {

                Configuration = configuration;

                HostEnvironment = hostEnvironment;

                //ConfigurationBuilder builder = new ConfigurationBuilder();

                //Configuration = builder.Build();

            }

            public IConfiguration Configuration { get; }

            protected IApplicationBuilder ApplicationBuilder { get; private set; }

            public IHostEnvironment HostEnvironment { get; }

            // This method gets called by the runtime. Use this method to add services to the container.

            public void ConfigureServices(IServiceCollection services)

            {

                //            services.AddRazorPages();

                // This is cookie authentication service.

                // [ Old Version #3 ]

                //services.AddIdentity<ApplicationUser, IdentityRole<Guid>>(options => {

                //    // [ Old version #1 ]

                //    //options.Cookies.ApplicationCookie.LoginPath = new PathString("/Home/Index");

                //    //options.Cookies.ApplicationCookie.SlidingExpiration = true;

                //    //options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromMinutes(this.Configuration.GetValue<int?>("Authentication:SlidingExpirationTime").Value);

               //    //options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Home/AccessDenied");

                //    // [ Old version #2 ]

                //    //options.Password.RequireUppercase = false;

                //    //options.Password.RequireLowercase = false;

                //    //options.Password.RequireNonAlphanumeric = false;

                //    //options.Password.RequireDigit = false;

                //    //options.Password.RequiredLength = 7;

                //})

                // [ Old Version #3 ]

                //.AddEntityFrameworkStores<ApplicationContext, Guid>()

                //.AddDefaultTokenProviders();

                // [ Old Version #3 - replacement ]

                services.AddDefaultIdentity<ApplicationUser>()  // "ApplicationUser" is named incorrectly, it should be "IdentityUser" instead, as per Microsoft documentation.

                    .AddRoles<IdentityRole<Guid>>()

                    .AddEntityFrameworkStores<ApplicationContext, Guid>()  // FYI - AddEntityFrameworkStores() deal with role that derives from IdentityRole, as per documentation.

                    //.AddDefaultUI()

                   .AddDefaultTokenProviders();

                // [ Old version #1 - replacement ]

                services.ConfigureApplicationCookie(options =>

                {

                    options.LoginPath = new PathString("/Home/Index");

                    options.SlidingExpiration = true;

                    options.ExpireTimeSpan = TimeSpan.FromMinutes(this.Configuration.GetValue<int?>("Authentication:SlidingExpirationTime").Value);

                    options.AccessDeniedPath = new PathString("/Home/AccessDenied");

                });

                // [ Old version #2 - replacement ]

                services.Configure<IdentityOptions>(options =>

                {

                    options.Password.RequireUppercase = false;

                    options.Password.RequireLowercase = false;

                    options.Password.RequireNonAlphanumeric = false;

                    options.Password.RequireDigit = false;

                    options.Password.RequiredLength = 7;

                });

                services.AddMvc();

                services.AddSession();

                //services.Configure<AuthorizationOptions>(options =>

                //{

                //});

            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

            {

                if (env.IsDevelopment())

                {

                    app.UseDeveloperExceptionPage();

                }

                else

                {

                    app.UseExceptionHandler("/Error");

                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

                    app.UseHsts();

                }

                app.UseHttpsRedirection();

                app.UseStaticFiles();

                app.UseRouting();

                app.UseAuthorization();

                app.UseEndpoints(endpoints =>

                {

                    endpoints.MapRazorPages();

                });

                // Config Exception.

                if (env.IsDevelopment())

                    app.UseDeveloperExceptionPage();

                else

                    app.UseExceptionHandler("/Home/ErrorPage.html");

                app.UseStaticFiles(); // Note, we are not authenticating for static files if this is before them

                app.UseSession();

                app.UseAuthentication();

                // MVC.

                //app.UseMvc(routes => routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"));

            }

        }

    }

    public class ApplicationUser : IdentityUser<Guid>, IUser

    {

    }

    public interface IUser

    {

    }

    public class ApplicationContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>

    {

        public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)

        {

        }

    protected override void OnModelCreating(ModelBuilder builder)

        {

           base.OnModelCreating(builder);

        }

    }

    <Project Sdk="Microsoft.NET.Sdk.Web">

      <PropertyGroup>

      <TargetFramework>netcoreapp3.1</TargetFramework>

      </PropertyGroup>

      <ItemGroup>

        <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />

        <PackageReference Include="Microsoft.AspNetCore.DataProtection" Version="3.1.3" />

        <PackageReference Include="Microsoft.AspNetCore.DataProtection.AzureStorage" Version="1.0.2" />

        <PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.2" />

        <PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="1.1.3" />

       <PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />

        <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />

        <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.1.3" />

        <PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="3.1.3" />

        <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.3" />

        <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.3" />

        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.3" />

        <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.3" />

        <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />

        <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.3" />

        <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />

        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.3" />

        <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />

        <PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="1.1.3" />

        <PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.2" />

        <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />

        <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />

        <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />

        <PackageReference Include="Microsoft.AspNetCore.AzureAppServicesIntegration" Version="1.0.2" />

    </ItemGroup>

    Tuesday, May 5, 2020 4:54 PM

Answers

  • User-854763662 posted

    Hi fletchsod2 ,

    AddDefaultIdentity extension method is used to add the default UI service for Razor Pages and MVC. From your installed packages, you forget to install the Microsoft.AspNetCore.Identity.UI package.

    Best Regards,

    Sherry

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 6, 2020 10:21 AM

All replies

  • User576623942 posted
    Have a look at this:
    https://stackoverflow.com/questions/56429882/blazor-iservicecollection-does-not-contain-a-definition-for-adddefaultidentity

    Try installing the package given in the comments.
    Tuesday, May 5, 2020 8:12 PM
  • User-854763662 posted

    Hi fletchsod2 ,

    AddDefaultIdentity extension method is used to add the default UI service for Razor Pages and MVC. From your installed packages, you forget to install the Microsoft.AspNetCore.Identity.UI package.

    Best Regards,

    Sherry

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 6, 2020 10:21 AM
  • User1428199325 posted

    pjanicked & Sherry Chen,

        Ok, that help by adding "Microsoft.AspNetCore.Identity.UI" NuGet package.   Now I have run into another error.  :-/   I can't make sense of this one.

    services.AddDefaultIdentity<ApplicationUser>() 
    .AddRoles<IdentityRole<Guid>>()
    .AddEntityFrameworkStores<ApplicationContext, Guid>() 
    .AddDefaultTokenProviders();

        The error on the first line is gone now.  But now new error on 3rd line here, "AddEntityFrameworkStore<ApplicationContext, Guid>()".   The error message is --> "IdentityBuilder" does not contain a definition for "AddEntityFrameworkStores" & no accessible extension method "AddEntityFrameworkStores" accepting a first argument of type "IdentityBuilder" could be found (are you mising a using directive or an assembly reference?).

       Not even sure what NuGet package does this "AddEntityFrameworkStores" come from & what have changed from version 1 to 3.1 either.

    Thanks.

    Wednesday, May 6, 2020 12:25 PM
  • User-474980206 posted

    The jump from core 1 to core 3 is large. You would be better off creating a new 3.1 app from the template with the basic features you want. Then you can compare the diffences in program.cs and startup.

    it may be easier to use the new project and add your old code to it.

    Wednesday, May 6, 2020 2:44 PM
  • User1428199325 posted

    I did that before with VS 2019 as new project & many are missing in there.  So that doesn't help either.   A kitchen sink sample would help me to get there faster.

    Wednesday, May 6, 2020 3:51 PM