【问题标题】:Nswag/Angular display API error message in error eventNswag/Angular 在错误事件中显示 API 错误消息
【发布时间】:2021-02-08 13:43:42
【问题描述】:

首先,我将 CQRS 架构用于后端 API,并使用 NSWAG 作为 API 连接;在服务代理中为前端 Angular 生成 API 端点。

我对我的 POST API 进行了简单的验证,在测试创建的 API 时,在 DevTools 中的结果有所不同。

在“网络”选项卡中,我期望的验证发生在“控制台”选项卡中 结果不一样;事实上,结果是我需要的。

这是我的问题。详细图片

API 调用代码

     saveLocationType(createLocationTypeCommand){
    this.tenantService.createLocationType(createLocationTypeCommand).subscribe(result => {
   // Do Something
    }, error => {
      console.log(error); 
    })
  }

这是来自我在网络选项卡中的 API 的正确验证结果。

这是我在控制台中的问题,这里的结果在网络选项卡中必须相同。

我相信控制台中的结果来自服务代理,因为它是为前端生成/格式化 API 的。

有没有办法配置 NSWAG 的生成服务代理?还是有其他方法可以在“网络”选项卡中的“控制台”选项卡中显示错误消息?

【问题讨论】:

    标签: angular nswag nswagstudio


    【解决方案1】:

    如果您使用 angular http 客户端,请尝试使用 responseType 文本选项。

    return this.http.post(url,body, {responseType: 'text'}).subscribe()
    

    客户端尝试将响应处理为 responseType: 'json' 作为默认值。 他尝试将此响应解析为 json,但失败并引发此错误。

    您可以在此处找到有关非 Json 响应体的更多信息:https://angular.io/guide/http#requesting-non-json-data

    【讨论】:

      【解决方案2】:

      我使用这些参考解决了我的问题:

      我为解决我的问题而实施的 C# Web API 中的片段

        [HttpPost("setup/locationType", Name = "createLocationType")]
              [ProducesResponseType((int)HttpStatusCode.OK)]
              [ProducesResponseType(typeof(ValidationProblemDetails), (int)HttpStatusCode.BadRequest)]
              public async Task<IActionResult> CreateLocationTypeAsync([FromBody] CreateLocationTypeCommand command)
              {
                  try
                  {
                      var commandResult = await _mediator.Send(command);
      
                      if (!commandResult)
                      {
                          return BadRequest();
                      }
      
                      return Ok();
                  }
                  catch(Exception ex)
                  {
                      var problemDetails = new ValidationProblemDetails
                      {
                          Status = (int)HttpStatusCode.BadRequest,
                          Type = "",
                          Title = "Create Location Type",
                          Detail = ex.Message,
                          Instance = HttpContext.Request.Path
                      };
      
                      return new ObjectResult(problemDetails)
                      {
                          ContentTypes = { "application/problem+json" },
                          StatusCode = (int)HttpStatusCode.BadRequest,
                      };
                  }
      
              }
      
      

      谢谢!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2023-04-02
        • 2018-01-12
        • 2018-07-07
        相关资源
        最近更新 更多