【发布时间】:2019-05-18 14:27:21
【问题描述】:
当 WebAPI 调用成功和失败时,我返回一个自定义对象。如何在客户端转换为该 WebAPI 的正确响应对象?万一出现异常。
[HttpPost]
public ActionResult<MyRespObject> PostTest([FromBody] MyPostObject obj)
{
try
{
MyRespObject response = SomeMethod(obj);
return this.ToActionResult(response);
}
catch (Exception ex) {
return this.ToActionResult(this.LoadMyRespObject(ex));
}
}
protected ActionResult<TResponse> ToActionResult<TResponse>(TResponse response)
where TResponse : IResponse
{
switch (response.Status)
{
case ResponseStatus.Success:
return this.Ok(response);
case ResponseStatus.InvalidRequest:
return this.BadRequest(response);
case ResponseStatus.NotFound:
return this.NotFound(response);
}
return this.StatusCode(500, response);
}
如果出现异常,如何在客户端将 ex 转换为 MyRespObject?我正在为 API 使用 autorest 生成客户端?
【问题讨论】:
-
万一出现异常。 --- 我建议您添加异常处理程序中间件,而不是创建明确的错误响应。这是使用 asp.net core web api 的标准方法
标签: c# asp.net-web-api asp.net-core-webapi