首页 > 解决方案 > HTTP 400:“输入字符串不是有效数字。”

问题描述

我正在使用 ASP.Net 后端访问数据库的 Angular 站点上工作,我收到此错误的区域是表单控件上的自定义异步验证器。验证器的目的是在允许用户提交表单之前检查数据库中是否存在输入 ID。

不过,奇怪的是,我在验证输入时并不总是收到这个错误,而且它在大多数情况下都能正常工作。我发现发生这种情况的一种情况是,如果字符串以“0”开头并在以下任何位置包含“8”或“9”,如果字符串以任何其他数字开头,那么它不会抛出 HTTP 400 错误。

在“01823”的情况下,我收到错误"{"":["Input string '01823' is not a valid number. Path '', line 1, position 5."]}"消息"Http failure response for https://localhost:5001/api/FS/vendor: 400 Bad Request"。错误中的position始终是字符串中的最后一个字符

数据库中确实存在符合这些条件的条目,无论输入是否存在都会发生错误。

验证方法

// Validate Vendor ID
invalidVendor(): AsyncValidatorFn {
  return (control: AbstractControl): | Observable<{ [key: string]: any } | null> | Promise<{ [key: string]: any } | null> => {
    if (control.value === null || control.value === '') {
      return of(null);
    }
    else {
      return control.valueChanges.pipe(
        debounceTime(500),
        take(1),
        switchMap(_ =>
          this.dbService.checkVendor(control.value).pipe(map(v =>
            v == '' ? { invalidVendor: { value: control.value } } : null)
          )
        )
      );
    }
  };
}

dbService.checkVendor

// Check for valid vendor ID
public checkVendor(vendor: string) {
  var httpOptions = {
    headers: { 'Content-Type': 'application/json' },
    responseType: 'text' as 'json'
  };
  return this.http.post<string>('api/FS/vendor', vendor, httpOptions);
}

FsController.ValidVendor

// POST: api/FS/vendor
[HttpPost("vendor")]
public async Task<ActionResult<string>> ValidVendor([FromBody] string vendor)
{
  var result = await _fsContext.FS_Vendor.Where(x => x.VendorID.Equals(vendor)).FirstOrDefaultAsync();
  return result != null ? result.VendorID : "";
}

更新:

我已经通过创建一个对象而不是使用 a 解决了这个问题,string但我仍然不知道为什么会发生这个特定问题,所以我会保持这个开放。

标签: c#asp.netangulartypescript

解决方案


推荐阅读