我正在使用.NET Core 2 Razor Pages和个人帐户身份验证进行Web应用。
我使用firstname扩展了我的数据库,因为它没有通过标准实现。一切都正常。但是,我想扩展我的/帐户/管理页面,以确保用户能够更改自己的名称。
OnGetAsync工作正常,但是当我的OnPostAsync无法正常工作时。
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (Input.Email != user.Email)
{
var setEmailResult = await _userManager.SetEmailAsync(user, Input.Email);
if (!setEmailResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
}
}
if (Input.PhoneNumber != user.PhoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
}
}
// not working yet
if (Input.FirstName != user.FirstName)
{
var setFirstNameResult = await MyManager.SetFirstNameAsync(user, Input.FirstName);
if (!setFirstNameResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting first name for user with ID '{user.Id}'.");
}
}
StatusMessage = "Your profile has been updated";
return RedirectToPage();
}
public class MyManager : UserManager<ApplicationUser>
{
public MyManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
{
}
public static async Task<IdentityResult> SetFirstNameAsync(ApplicationUser user, string FirstName)
{
if (user == null)
{
throw new ArgumentNullException(nameof(user));
}
if (FirstName == null)
{
throw new ArgumentNullException(nameof(FirstName));
}
user.FirstName = FirstName;
return IdentityResult.Success;
}
}
当我点击“保存”时,它失败了。按钮并告诉我我的个人资料已成功更新,但事实并非如此。它只保留了旧的名字值。我在这里缺少什么?
答案 0 :(得分:2)
您的方法不会执行类似的内置方法所做的操作:即,实际上将更改保留回数据库。您只需在用户上设置属性,然后返回成功。只要该实例超出范围,您为名字设置的值就会随之而来。
那就是说,@ CodeNotFound的评论很突出。没有理由这样做,你也不应该这样做。其他方法适用于特定用例。对于通常更新用户的属性,您只需设置相关属性,然后使用UpdateAsync
将用户保存回来。