.NET Core Razor Pages中用Setters扩展UserManager及修改用户名异常解决
Hey there! Let's tackle that OnPostAsync issue you're having with updating the FirstName in your Razor Pages account management page. Since you already got the database extension and OnGetAsync working, the problem is likely in one of these common spots—let's break it down step by step:
First, make sure your page's ViewModel (like IndexViewModel or a custom model) includes the FirstName property, with proper validation attributes if needed. Also double-check that your form is correctly binding to it:
ViewModel Example:
public class IndexViewModel { [Display(Name = "First Name")] [StringLength(50, ErrorMessage = "First name cannot exceed 50 characters.")] public string FirstName { get; set; } // Keep your existing properties like Email, PhoneNumber, etc. }
Form Input Example:
<div class="form-group"> <label asp-for="Input.FirstName" class="control-label"></label> <input asp-for="Input.FirstName" class="form-control" /> <span asp-validation-for="Input.FirstName" class="text-danger"></span> </div>
Note: Make sure your form uses the asp-page tag helper (or includes @Html.AntiForgeryToken()) to avoid anti-forgery validation failures.
OnPostAsync Logic The most common culprit is not properly fetching the user entity, updating its FirstName value, and saving changes. Here's a corrected version of your method:
public async Task<IActionResult> OnPostAsync() { // First, load the current user to get existing data if ModelState is invalid var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!ModelState.IsValid) { // Repopulate the ViewModel with existing user data to keep form values Input.FirstName = user.FirstName; // Repopulate other properties like Email/PhoneNumber here too return Page(); } // Check if FirstName actually changed if (Input.FirstName != user.FirstName) { user.FirstName = Input.FirstName; var updateResult = await _userManager.UpdateAsync(user); if (!updateResult.Succeeded) { // Add any errors from the update to ModelState foreach (var error in updateResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } } TempData["StatusMessage"] = "Your profile has been updated successfully!"; return RedirectToPage(); }
Key fixes here: We explicitly fetch the user entity, update its FirstName property, and call UpdateAsync to persist changes. We also handle update failures and repopulate the form if validation fails.
If ModelState.IsValid is always false, don't just return the page—check what's causing the failure. Add this block to your page to display all validation errors:
@if (!ModelState.IsValid) { <div class="alert alert-danger"> <h4>Please correct these errors:</h4> <ul> @foreach (var error in ModelState.Values.SelectMany(v => v.Errors)) { <li>@error.ErrorMessage</li> } </ul> </div> }
Common issues here include missing anti-forgery tokens, validation rules on FirstName being violated, or other hidden form fields failing validation.
Double-check that your ApplicationUser class includes the FirstName property and that your DbContext is correctly mapping it:
public class ApplicationUser : IdentityUser { public string FirstName { get; set; } }
Ensure you've applied the database migration that added the FirstName column (run Update-Database in the Package Manager Console if you haven't already).
内容的提问来源于stack exchange,提问作者M. Douglas

