当WebAPI调用成功或失败时,我将返回一个Custom对象。如何在客户端为此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生成客户端吗?
答案 0 :(得分:0)
将返回类型更改为
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; }
}
答案 1 :(得分:0)
如何在此WebAPI的客户端上转换为正确的响应对象?如有例外。
这就是中间件出现的地方。下面是您需要遵循的一般方法,该方法也可以在发生错误的情况下有效地处理请求。
万一发生错误,请大致像这样编写模型
Class Error {
int errorCode {get ;set;}
string message {get ;set;}
}
,因此您也可以修改此类以获取更多提示(如hint等)属性。 下面的链接具有更清晰,更好的说明。