首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >IServiceCollection不包含AddDefaultIdentity的定义

IServiceCollection不包含AddDefaultIdentity的定义
EN

Stack Overflow用户
提问于 2020-05-06 01:34:48
回答 2查看 14.7K关注 0票数 9

知道为什么会出现这个错误吗?错误消息--> "IServiceCollection不包含AddDefaultIdentity的定义“

代码语言:javascript
运行
复制
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);
    }
}
代码语言:javascript
运行
复制
<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>
</Project>

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

好的,这有助于添加"Microsoft.AspNetCore.Identity.UI“NuGet包。现在我遇到了另一个错误。:-/我搞不懂这个。

代码语言:javascript
运行
复制
services.AddDefaultIdentity<ApplicationUser>() 
.AddRoles<IdentityRole<Guid>>()
.AddEntityFrameworkStores<ApplicationContext, Guid>() 
.AddDefaultTokenProviders();

第一行上的错误现在消失了。但是现在第三行出现了新的错误,"AddEntityFrameworkStore()“。错误消息是--> "IdentityBuilder“不包含"AddEntityFrameworkStores”的定义&找不到可访问的扩展方法"AddEntityFrameworkStores“,该方法接受类型为"IdentityBuilder”的第一个参数(您是否遗漏了using指令或程序集引用?)。

甚至不确定这个"AddEntityFrameworkStores“来自哪个NuGet包&从版本1到3.1也发生了哪些变化。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-06 03:39:17

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

-编辑

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

  1. 将整个解决方案移动到备份文件夹(请确保将源代码管理文件保留在原来的位置)。
  2. 将在原始位置创建一个新应用程序,其名称与目标3.1的名称完全相同。我使用VS2019中的“网络应用程序(模型-视图-控制器)”模板,并将身份验证更改为“针对源代码控制的单个用户Accounts".
  3. Commit”,以便您可以看到所做的更改。
  4. 将所有页面、视图、控制器和其他代码复制回新的nuget packages.
  5. You可能需要对复制的代码进行一些更改,但您可以使用源代码控制和迁移文档中的更改作为参考点。

让它正常工作仍然需要很多时间,否则你将需要检查每个迁移文档,从1.x到2.0的迁移文档一直到3.0到3.1的迁移文档。

票数 13
EN

Stack Overflow用户

发布于 2021-02-27 16:54:21

我不知道这是什么时候加入的,但在AspNetCore 5.0中:services.AddIdentityCore<ApplicationUser>()可以工作。仅包含TUser的类型要求。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61619369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档