来自WebAPI Blazor(服务器端)调用的处理ModelState错误

时间:2019-07-30 15:45:36

标签: asp.net-core-webapi modelstate blazor-server-side

当我进行WebAPI调用时,我想了解如何将ModelState错误传递回我的Blazor应用程序。

DataAnnotations都可以正确验证,但是,如果我执行任何其他类型的验证(一次经过ModelState.IsValid调用),我将无法获得添加到ModelState并传递回Blazor的那些错误。我想念什么?

Blazor页面

...
   <EditForm Model="@_user" OnValidSubmit="@Update">
      <DataAnnotationsValidator />
      <ValidationSummary />
      <div class="container">
         <div class="row">
            <div class="col-md-3">Name:</div>
            <div class="col-md-9"><InputText id="Name" @bind-Value="@_user.UserName" class="form-control" /></div>
         </div>
         @if (_user.isNew)
         {
         <div class="row">
            <div class="col-md-3">Password:</div>
            <div class="col-md-9"><InputText id="Name" @bind-Value="@_user.Password" class="form-control" type="password" /></div>
         </div>
         <div class="row">
            <div class="col-md-3">Validate your password:</div>
            <div class="col-md-9"><InputText id="Name" @bind-Value="@_user.ValidatePassword" class="form-control" type="password" /></div>
         </div>
         }
         <div class="row">
            <div class="col-md-3">Email:</div>
            <div class="col-md-9"><InputText id="Name" @bind-Value="@_user.Email" class="form-control" /></div>
         </div>
         <div class="row">
            <div class="col-md-3">Roles:</div>
            <div class="col-md-9">
               @foreach (IdentityRole role in _roles)
               {
                  bool isChecked = _user.UserRoles.Any(r => r.Id == role.Id);
                  <input type="checkbox" Id="@role.Id" name="@role.Id"
                         Class="form-control" checked="@isChecked" @onchange="@(e => RoleChecked(e, role.Id))" />
                  @role.Name
               }
            </div>
         </div>
         <button type="submit" class="btn btn-@buttonClass">@buttonText</button>
      </div>
   </EditForm>
}

@functions {
   [Parameter]
   string id { get; set; } = "";
   private UserViewModel _user { get; set; }
...
   private async Task Update()
   {
      if (id != "")
      {
         await apiClient.UpdateUserAsync(_user);
      }
      else
      {
         await apiClient.AddUserAsync(_user);
      }
      UriHelper.NavigateTo("admin/users");
   }
...

WebAPI控制器

[HttpPost]
      public async Task<IActionResult> Post([FromBody] UserViewModel applicationUser)
      {
         if (applicationUser == null)
         {
            _logger.LogError($"ApplicationUser object null");
            return BadRequest("ApplicationUser object is null");
         }
         if (!ModelState.IsValid)
         {
            _logger.LogWarn("ApplicationUser object invalid");
            return BadRequest(ModelState);
         }
         else
         {
            _logger.LogDebug($"Creating ApplicationUser {applicationUser.UserName}");
            var obj = new ApplicationUser();
            obj.Map(applicationUser);
            IdentityResult result = await _userManager.CreateAsync(obj, applicationUser.Password);
            if (result.Succeeded)
            {
               //put the newly created user back on top of the parameter for role creation
               applicationUser.Map(obj);
               await IdentityHelpers.UpdateUserRoles(_userManager, applicationUser);
               return CreatedAtRoute("", new { id = applicationUser.Id }, applicationUser);
            }
            else
            {
               _logger.LogWarn("ApplicationUser object could not be created");
               result.Errors.ToList().ForEach(e => ModelState.AddModelError(e.Code, e.Description));
               return BadRequest(ModelState);
            }
         }
      }

我如何将ModelState错误传回Blazor,以便它以与DataAnnotations(或模型验证)相同的方式响应错误?

0 个答案:

没有答案