【问题标题】:ASP NET Core 2.0 + angular 4 json response handleASP NET Core 2.0 + angular 4 json 响应句柄
【发布时间】:2018-05-29 09:36:41
【问题描述】:

我有 ASP NET Core 2.0 项目。对于客户端,我使用 Angular 4。我尝试在客户端实现 api 请求句柄。

所以,在我的控制器中,我有

public IActionResult AddWorkSchedule(int employeeId, [FromBody] WorkScheduleBaseRequest request)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    return Ok();
}

所以,我正在等待在客户端获取错误数组,但我将其作为文本获取。

我在 agular 4 中使用 net httpClient 并像这样调用 api

addWorkSchedule(employeeId: number, workSchedule: WorkSchedule): Promise<any> {
        return this.http
            .post('/api/employee/' + employeeId + '/workschedule/', workSchedule, { observe: 'response', responseType: 'json' })
            .toPromise();
    }

并以这种方式在我的组件中处理它

this.employeeService
    .addWorkSchedule(this.employee.employeeId, workSchedule).then(
    (success) => {
        console.log(success);
        },
        (error: HttpErrorResponse) => {
            console.log(error);
            console.log(error.error);
        });

我的问题是为什么 'error' 属性是文本,而不是数组,而错误响应,我该怎么做才能让它像数组一样?

提前致谢。

【问题讨论】:

  • 但您返回的是 badrequest 而不是一系列错误。答案就在你的回报中。错误文本来自您的 API 验证
  • 即使我以这种方式返回响应 "return StatusCode(StatusCodes.Status400BadRequest, new[] {"error1", "error2"})" - 我没有数组
  • 是的,那是因为您正在返回状态码,要返回错误,您应该在您的操作中返回一个数组,并将其作为 json 在您的 web/angular 中读取,就像您读取任何请求/响应一样从假设数据库

标签: angular asp.net-core angular4-httpclient


【解决方案1】:

我发现了问题,这是 Angular 4 中 httpClient 的错误。更多详细信息问题在 https://github.com/angular/angular/issues/19888 中描述。简而言之 - 错误响应属性“错误”的类型错误。

我完成的解决方案:

this.employeeService
            .addWorkSchedule(this.employee.employeeId, workSchedule).then(
                (success) => {
                    console.log(success);
                },
                (error: HttpErrorResponse ) => {
                    let json = JSON.parse(error.error); // parse it to json as requested type is json
                    console.log(json); // json object
                    console.log(json.length); // json objects count == string errors count that came from server
                });

【讨论】:

    【解决方案2】:
    this._Http.post(this._baseUrl + "api/Employee/Create", this.CreateDTO.value,
                {
                    responseType: 'text'
                }).subscribe(result => { alert(result) });
    

    添加 {responseType:'text'} 对我有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-08
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2019-07-10
      • 2018-03-27
      • 2018-11-20
      相关资源
      最近更新 更多