Я работаю с ASP.NET Core Identity и скопировал ResetPassword.cshtml в ActivateAccount.cshtml и внес некоторые изменения в копию .
Теперь, когда я отправляю электронное письмо для сброса пароля со ссылкой на новую страницу, я получаю исключение. Но также я получаю то же исключение, когда использую функцию «Забыли пароль» для доступа к исходной странице. (До моих изменений «Забыли пароль» работало нормально.)
Исключение
Невозможно разрешить службу для типа «Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]» при попытке активировать «Pegasus.Areas.Identity.Pages.Account.ResetPasswordModel».
Я считаю, что это связано с настройкой внедрения зависимостей с помощью UserManager и Identity с использованием UserManager. Но я не могу понять, как мои изменения привели к этой ошибке.
Может ли кто-нибудь помочь объяснить, что я здесь вижу?
Stack Trace
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(Type type, Type requiredBy)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.c__DisplayClass3_0.b__0(PageContext pageContext)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.CreateInstance()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.d__21.MoveNext()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.d.MoveNext()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.d.MoveNext()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.d.MoveNext()
at PegasusBusinessLayer.Services.TrackUserActivity.d__5.MoveNext() in
C:\Users\****\Services\TrackUserActivity.cs:line 50
Конфигурация внедрения зависимостей
builder.Services.AddDefaultIdentity(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddRoles()
.AddEntityFrameworkStores();
ResetPassword.cshtml.cs
public class ResetPasswordModel : PageModel
{
private readonly UserManager _userManager;
public ResetPasswordModel(UserManager userManager)
{
_userManager = userManager;
}
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[BindProperty]
public InputModel Input { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
public class InputModel
{
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[Required]
[EmailAddress]
public string Email { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[Required]
public string Code { get; set; }
}
public IActionResult OnGet(string code = null)
{
if (code == null)
{
return BadRequest("A code must be supplied for password reset.");
}
else
{
Input = new InputModel
{
Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code))
};
return Page();
}
}
public async Task OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.FindByEmailAsync(Input.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToPage("./ResetPasswordConfirmation");
}
var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password);
if (result.Succeeded)
{
return RedirectToPage("./ResetPasswordConfirmation");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
}
ActivateAccount.cshtml.cs
private readonly UserManager UserManager;
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[BindProperty]
public InputModel Input { get; set; }
public ActivateAccountModel(UserManager userManager)
{
UserManager = userManager;
}
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
public class InputModel
{
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[Required]
[EmailAddress]
public string Email { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
///
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
///
[Required]
public string Code { get; set; }
}
public IActionResult OnGet(string code = null, string email = null)
{
if (code == null)
return BadRequest("A code must be supplied for account activation.");
// Email is expected by user can type it in if not
Input = new InputModel
{
Email = email,
Code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code))
};
return Page();
}
public async Task OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await UserManager.FindByEmailAsync(Input.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToPage("./ResetPasswordConfirmation");
}
var result = await UserManager.ResetPasswordAsync(user, Input.Code, Input.Password);
if (result.Succeeded)
{
return RedirectToPage("./ResetPasswordConfirmation");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return Page();
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... -exception
Невозможно разрешить исключение UserManager ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Измените ключ IdentityUser со строки на GUID — UserManager больше не работает.
Anonymous » » в форуме C# - 0 Ответы
- 28 Просмотры
-
Последнее сообщение Anonymous
-