mah*_*thy 7 c# asp.net asp.net-core
我在 mac 机器上使用 asp.net 核心,我试图为我的 asp.net mvc web 应用程序创建一个自定义的 ApplicationUser,它与基本 IdentityUser 一起工作得非常好。
尽管遵循 Microsoft 的本指南:
我面临这个错误:
{"error":"没有注册'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'类型的服务。"}
以下是我的代码片段:
启动文件
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// [...]
services.AddDbContext<ApplicationDbContext>(
options => options.UseSqlServer(identityDbContextConnection));
// Relevant part: influences the error
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
Run Code Online (Sandbox Code Playgroud)
应用程序用户.cs
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
[Required]
public string DrivingLicense { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
注册.cshtml.cs
public class RegisterModel : PageModel
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IServiceProvider _services;
public RegisterModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<RegisterModel> logger,
IServiceProvider services
)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_services = services;
}
[BindProperty]
public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
// Added for ApplicationUser
[Required]
[Display(Name = "Driving License")]
public string DrivingLicense { get; set; }
// -----------------------------
// [...]
}
public void OnGet(string returnUrl = null)
{
ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = new ApplicationUser {
UserName = Input.Email,
Email = Input.Email,
DrivingLicense = Input.DrivingLicense // property added by ApplicationUser
};
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return Page();
}
}
Run Code Online (Sandbox Code Playgroud)
来自Manage/Index.cshtml.cs 的片段
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
// Added for ApplicationUser
[Required]
[Display(Name = "Driving License")]
public string DrivingLicense { get; set; }
// -----------------------------
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
// [...]
// Added for ApplicationUser
if (Input.DrivingLicense != user.DrivingLicense)
{
user.DrivingLicense = Input.DrivingLicense;
}
await _userManager.UpdateAsync(user);
// -------------------------
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your profile has been updated";
return RedirectToPage();
}
Run Code Online (Sandbox Code Playgroud)
应用程序数据库上下文
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
Run Code Online (Sandbox Code Playgroud)
我无法从官方微软指南中遵循的唯一部分是编辑 Account/Manage/Index.cshtml,因为在我执行 CLI 步骤时该文件没有搭建!
值得注意的是,当我在startup.cs中用 IdentityUser 替换 ApplicationUser 时,如下所示:
services.AddIdentity<IdentityUser, IdentityRole>()应用程序打开但当然注册没有按预期正常工作。
Ola*_*vid 10
问题出在“_LoginPartial.cshtml”中
删除这个
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
Run Code Online (Sandbox Code Playgroud)
添加这个
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
Run Code Online (Sandbox Code Playgroud)
在 dotnet core 2.1 中我遇到了同样的问题,以下步骤解决了我的问题
1)扩展IdentityUser或IdentityRole
public class ApplicationUser : IdentityUser<Guid>
{
public DateTime JoinTime { get; set; } = DateTime.Now;
public DateTime DOB { get; set; } = Convert.ToDateTime("01-Jan-1900");
}
public class ApplicationRole : IdentityRole<Guid>
{
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
2)更新ApplicationDbContext类
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
Run Code Online (Sandbox Code Playgroud)
3)更新Stratup.csConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
}
Run Code Online (Sandbox Code Playgroud)
更新 _LoginPartial.cshtml (共享 --> 查看)
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7908 次 |
| 最近记录: |