Blazor Server表单绑定失效求助:Login方法中UserCred值为空
Blazor Server中EditForm绑定值为空的问题修复
问题现象
开发Blazor Server项目时,Login方法可正常触发,但UserCred的UserName和Password始终为空字符串(非null)。浏览器调试显示POST请求已携带正确的表单数据,但组件绑定未生效。
问题根源与修复方案
1. 缺少验证组件导致模型绑定失败
Blazor的EditForm必须配合验证组件(如DataAnnotationsValidator)才能完成模型绑定流程,即使不需要业务验证,也需要添加该组件启用绑定逻辑。
修改Home.razor中的EditForm部分:
@if (!CurrentUser.IsInRole(TUser.AccessRights.User.ToString()) && !CurrentUser.IsInRole(TUser.AccessRights.Admin.ToString())) { <EditForm Model="UserCred" FormName="Login" OnValidSubmit="@Login"> <DataAnnotationsValidator /> <!-- 添加此组件启用模型绑定 --> <div class="form-group"> <label for="userName" class="col-form-label col-md-2">Nom d'utilisateur</label> <div class="col-md-10"> <InputText id="userName" @bind-Value="UserCred.UserName" /> </div> </div> <div class="form-group"> <label for="password" class=" col-form-label col-md-2">Mot de passe</label> <div class="col-md-10"> <InputText id="password" @bind-Value="UserCred.Password" type="password" /> </div> </div> <br /> <button type="submit" class="btn btn-primary btn-sm">Connexion</button> </EditForm> }
2. 异步方法阻塞导致状态异常
SignInAsync是异步方法,使用.Wait()会阻塞线程,可能引发组件状态更新异常,改为await调用:
// 替换原有的.Wait()调用 await _httpContextAccessor!.HttpContext!.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
3. 修复登录逻辑的流程错误
登录成功后无需重复执行导航和错误信息设置,调整代码逻辑确保仅在失败时触发错误流程:
public async Task Login() { try { _logger!.LogInformation($"Login : {UserCred.UserName}, {UserCred.Password}"); if (!string.IsNullOrEmpty(UserCred.UserName) && !string.IsNullOrEmpty(UserCred.Password)) { using DBInterface dbManager = new(); TUser? dbUser = dbManager.GetAllUsers().FirstOrDefault(u => string.Compare(UserCred.UserName, u.Name, true) == 0); if (dbUser != null && Simple3Des.DecryptString(dbUser.PasswordHash) == UserCred.Password) { _logger!.LogInformation("Login de l'utilisateur {user}", dbUser.Name); List<Claim> claims = [ new(ClaimTypes.Name, UserCred.UserName), new(ClaimTypes.Role, dbUser.AccessLevelEnu.ToString()) ]; ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); AuthenticationProperties authProperties = new() { AllowRefresh = true, IsPersistent = true, }; await _httpContextAccessor!.HttpContext!.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); _navigationManager!.NavigateTo("/"); return; // 登录成功直接返回,跳过后续错误逻辑 } } // 仅在登录失败时设置错误信息 Message = $"Nom d'utilisateur ou mot de passe invalide !"; } catch (Exception ex) { _logger!.LogError("Erreur dans {methodName} : {exceptionType} : {exceptionMessage}", $"{nameof(Home)}.{nameof(Login)}", ex.GetType().Name, ex.Message); Message = "Une erreur est survenue lors de la connexion."; throw; } _navigationManager!.NavigateTo("/"); }
4. 确保模型类初始化正确
显式添加无参构造函数,保证UserId实例化时属性初始化正常:
public class UserId { public UserId() { UserName = string.Empty; Password = string.Empty; } public string UserName { get; set; } public string Password { get; set; } }
内容的提问来源于stack exchange,提问作者jérôme Courbat
相关产品推荐
相关产品推荐

