ASP.NET Core WebApi将错误消息返回给AngularJS $http promise

前端之家收集整理的这篇文章主要介绍了ASP.NET Core WebApi将错误消息返回给AngularJS $http promise前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将异常消息返回给AngularJS UI.
作为后端,我使用ASP.NET Core Web Api控制器:
  1. [Route("api/cars/{carNumber}")]
  2. public string Get(string carNumber)
  3. {
  4. var jsonHttpResponse = _carInfoProvider.GetAllCarsByNumber(carNumber);
  5. if (jsonHttpResponse.HasError)
  6. {
  7. var message = new HttpResponseMessage(HttpStatusCode.InternalServerError)
  8. {
  9. Content = new StringContent(jsonHttpResponse.ErrorMessage)
  10. };
  11.  
  12. throw new HttpResponseException(message);
  13. }
  14.  
  15. return jsonHttpResponse.Content;
  16. }

但在Angular方面,失败承诺只能看到状态和statusText“内部服务器错误”:

如何将错误消息传递给Core Web Api的Angular $http失败承诺?

解决方法

除非你正在做一些 exception filtering,否则抛出新的HttpResponseException(消息)将成为未捕获的异常,它将作为通用500内部服务器错误返回到您的前端.

您应该做的是返回状态代码结果,例如BadRequestResult.这意味着您的方法不需要返回字符串,而是需要返回IActionResult:

  1. [Route("api/cars/{carNumber}")]
  2. public IActionResult Get(string carNumber)
  3. {
  4. var jsonHttpResponse = _carInfoProvider.GetAllCarsByNumber(carNumber);
  5. if (jsonHttpResponse.HasError)
  6. {
  7. return BadRequest(jsonHttpResponse.ErrorMessage);
  8. }
  9.  
  10. return Ok(jsonHttpResponse.Content);
  11. }

另请参阅:我在how to return uncaught exceptions as JSON的答案.(如果您希望将所有未捕获的异常作为JSON返回.)

猜你在找的.NET Core相关文章