【发布时间】:2022-01-08 21:50:51
【问题描述】:
我目前正在尝试结合 MongoDB 学习 ASP.NET Core 3.1。我已经可以执行简单的 CRUD 操作了。现在我想设置与 MongoDB 相关的 ASP.NET Core Identity。为此,我安装了以下 Nuget 包:
- AspNetCore.Identity.Mongo(8.1.0 版)
- AspNetCore.Identity.MongoDbCore(版本 3.1.1)
在 Configure 方法的 IdentityHostingStartup 类中,我现在正在执行以下代码:
builder.ConfigureServices((context, services) => {
services.AddIdentityMongoDbProvider<ApplicationUser, MongoRole>(identityOptions =>
{
// Password settings.
identityOptions.Password.RequiredLength = 6;
identityOptions.Password.RequireLowercase = true;
identityOptions.Password.RequireUppercase = true;
identityOptions.Password.RequireNonAlphanumeric = false;
identityOptions.Password.RequireDigit = true;
// Lockout settings.
identityOptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
identityOptions.Lockout.MaxFailedAccessAttempts = 5;
identityOptions.Lockout.AllowedForNewUsers = true;
// User settings.
identityOptions.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
identityOptions.User.RequireUniqueEmail = true;
}, options => {
options.ConnectionString = "mongodb://localhost:27017/MyDB";
options.UsersCollection = "ApplicationUser";
options.RolesCollection = "clientRole";
}).AddDefaultUI();
// This is required to ensure server can identify user after login
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
});
但我在编译之前收到以下错误:
“MongoIdentityOptions”不包含“Password”的定义,并且找不到接受“MongoIdentityOptions”类型的第一个参数的可访问扩展方法“Password”(您是否缺少 using 指令或程序集引用?)
我从here获得了代码。
我尝试先注释掉对 identityOptions 的所有访问。但是在编译代码之前出现以下错误:
“Application.Areas.Identity.Data.ApplicationUser”不能用作泛型类型或方法“MongoIdentityExtensions.AddIdentityMongoDbProvider
(IServiceCollection, Action, Action)”中的类型参数“TUser”。没有从“Application.Areas.Identity.Data.ApplicationUser”到“AspNetCore.Identity.Mongo.Model.MongoUser”的隐式引用转换。
我做错了什么?
【问题讨论】:
-
嗨阿里!对我来说,启动代码看起来有点尴尬(我希望使用
ConfigureServices方法)。为了帮助您,我们可能需要获取整个 startup.cs 代码。但是,我发现了一个基于 .NET 5 的工作演示:github.com/matteofabbri/AspNetCore.Identity.Mongo/tree/master/…
标签: c# asp.net mongodb asp.net-core identity