本文介绍了IServiceCollection不包含AddDefaultIdentity的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

知道我为什么会收到此错误吗?错误消息->"IServiceCollection不包含AddDefaultIdentity的定义"

我正在从.NET Core v1.1迁移到v3.1

 公共类程序{公共异步静态void Main(string [] args){等待Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => {webBuilder.UseContentRoot(Directory.GetCurrentDirectory());webBuilder.UseKestrel();webBuilder.UseAzureAppServices();webBuilder.UseStartup< Startup>();}).建造().RunAsync();}}公共类创业{公共启动(IConfiguration配置,IHostEnvironment hostEnvironment){配置=配置;HostEnvironment = hostEnvironment;}公共IConfiguration配置{}受保护的IApplicationBuilder ApplicationBuilder {get;私人套装;}公共IHostEnvironment HostEnvironment {get;}//此方法由运行时调用.使用此方法将服务添加到容器.公共无效ConfigureServices(IServiceCollection服务){//services.AddRazorPages();services.AddDefaultIdentity< ApplicationUser>()//根据Microsoft文档,"ApplicationUser"的命名错误,应改为"IdentityUser"..AddRoles< IdentityRole< Guid>>().AddEntityFrameworkStores< ApplicationContext,Guid>()////仅供参考-根据文档,AddEntityFrameworkStores()处理从IdentityRole派生的角色.//.AddDefaultUI().AddDefaultTokenProviders();//[旧版本#1-替换]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");});//[旧版本#2-替换]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 =>//{//});}//此方法由运行时调用.使用此方法来配置HTTP请求管道.公共无效配置(IApplicationBuilder应用程序,IWebHostEnvironment env){如果(env.IsDevelopment()){app.UseDeveloperExceptionPage();}别的{app.UseExceptionHandler("/Error");}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapRazorPages();});//配置异常.如果(env.IsDevelopment())app.UseDeveloperExceptionPage();别的app.UseExceptionHandler("/Home/ErrorPage.html");app.UseStaticFiles();//注意,如果静态文件不在静态文件之前,我们就不会对其进行身份验证app.UseSession();app.UseAuthentication();//MVC.//app.UseMvc(routes => route.MapRoute("default","{controller = Home}/{action = Index}/{id?}"));}}公共类ApplicationUser:IdentityUser< Guid> ;, IUser{}公共接口IUser{}公共类ApplicationContext:IdentityDbContext< ApplicationUser,IdentityRole< Guid>,Guid>.{公共ApplicationContext(DbContextOptions< ApplicationContext>选项):基础(选项){}受保护的重写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"/>< PackgaeReference 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> 

-已编辑-下面的新更新.-------------------------------------------------------

好的,可以通过添加"Microsoft.AspNetCore.Identity.UI" NuGet程序包来提供帮助.现在,我遇到了另一个错误.:-/我对这个一无所知.

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

第一行的错误现在消失了.但是,现在第三行出现新错误"AddEntityFrameworkStore()".错误消息是->"IdentityBuilder"不包含"AddEntityFrameworkStores"的定义.找不到包含第一个类型为"IdentityBuilder"的自变量的可访问扩展方法"AddEntityFrameworkStores"(您是在误使用using指令还是程序集引用?).

甚至不确定此"AddEntityFrameworkStores"来自&从版本1到3.1都有什么变化.

解决方案

您需要添加对 Microsoft.AspNetCore.Identity.UI nuget程序包,以便使用 AddDefaultIdentity .但是,如果您不想迁移到Identity Razor类库,我认为您仍然可以在核心3.1中使用 .AddIdentity< ApplicationUser,IdentityRole>().如果确实要迁移到RCL,则从2.0到2.1的迁移文档可能是一个很好的起点: https://docs.microsoft.com/zh-CN/aspnet/core/migration/20_21?view=aspnetcore-3.1#changes-to-authentication-code

---编辑---

我已经将一些站点从1.1迁移到3.1,而我发现最简单的方法是:

  1. 将整个解决方案移至备份文件夹(确保将源代码控制文件保留在原处).
  2. 使用与3.1完全相同的名称在您的原始位置创建一个新应用程序.我在VS 2019中使用"Web应用程序(模型-视图-控制器)"模板,并将身份验证更改为个人用户帐户".
  3. 将其提交给源代码管理,以便您可以看到所做的更改.
  4. 将所有页面,视图控制器和其他代码复制到新应用程序中.
  5. 重新添加所有丢失的nuget程序包.
  6. 您可能需要对复制的代码进行一些更改,但是您可以将源代码管理和迁移文档中的更改用作参考点.

要使其正常工作还需要花费很多时间,否则您将需要遍历每一个迁移文档,从1.x到2.0的迁移文档一直到3.0到3.1的文档.

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

I'm migrating from .NET Core v1.1 to v3.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;
    }

    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();

        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");
        }

        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" />
    <PackgaeReference 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>

-- Edited - New Update Below. -------------------------------------------------------

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()". 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.

解决方案

You would need to add a reference to the Microsoft.AspNetCore.Identity.UI nuget package in order to use AddDefaultIdentity. But if you don't want to migrate to the Identity Razor Class Library I think you can still use .AddIdentity<ApplicationUser, IdentityRole>() in core 3.1. If you do want to migrate to the RCL, the Migration documentation for 2.0 to 2.1 might be a good starting place:https://docs.microsoft.com/en-us/aspnet/core/migration/20_21?view=aspnetcore-3.1#changes-to-authentication-code

--- Edited ---

I've migrated a few sites from 1.1 to 3.1 and the easiest way I have found to do it is this:

  1. Move your entire solution to a backup folder (make sure to leave your source control files where they are).
  2. Create a new application in your original location with the exact same name that targets 3.1. I use the "Web Application (Model-View-Controller)" template in VS 2019 and change the authentication to "Individual User Accounts".
  3. Commit that to source control so you can see what changes you make.
  4. Copy all of your pages, views controllers, and other code to the new application.
  5. Add back any missing nuget packages.
  6. You will probably need to make some changes to your copied code but you can use the changes in source control and the migration docs for a reference point.

It still takes a lot to get it working but otherwise you will need to go through every migration doc starting with the one for 1.x to 2.0 all the way through the doc for 3.0 to 3.1.

这篇关于IServiceCollection不包含AddDefaultIdentity的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:17