【问题标题】:WebAPI exception return type objectWebAPI 异常返回类型对象
【发布时间】: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


【解决方案1】:

返回类型更改为

HttpResponseMessage

然后客户端可以检查数据的状态

您的代码将是

 public HttpResponseMessage PostTest([FromBody] MyPostObject obj)
{
    try
    {
    ResponseModel _objResponseModel = new ResponseModel();
        MyRespObject response = SomeMethod(obj);

        return this.ToActionResult(response);

    _objResponseModel.Data = response;
            _objResponseModel.Status = response.Status;
            _objResponseModel.Message = "success";
    }
    catch (Exception ex) {
        _objResponseModel.Data = null;
            _objResponseModel.Status = false;
            _objResponseModel.Message = "failed";
    }
 return Request.CreateResponse(HttpStatusCode.OK, _objResponseModel);
}
}  
  public class ResponseModel
{
    public string Message { set; get; }
    public bool Status { set; get; }
    public object Data { set; get; }

}

【讨论】:

    【解决方案2】:

    如何在客户端将此 WebAPI 转换为正确的响应对象?万一出现异常。

    这就是中间件发挥作用的地方。以下是您需要遵循的一般方法,该方法也可以在出现错误时有效地处理请求。

    • 定义 ErrorHandlingMiddleware 这是一个异步自定义类。
    • 然后在 Startup.cs 中注册这个类作为中间件,这样每一个请求都会通过这个中间件。
    • 万一出错,一般这样写模型

        Class Error { 
               int errorCode {get ;set;}        
               string message {get ;set;}
         }
      

      所以你也可以修改这个类以获得更多的属性,比如提示等。 下面的链接有更清晰和很好的解释。

    https://code-maze.com/global-error-handling-aspnetcore/

    ASP.NET Core Web API exception handling

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2010-10-24
      • 2017-07-22
      • 2013-10-30
      • 2011-03-21
      • 1970-01-01
      • 2017-02-24
      相关资源
      最近更新 更多