正常响应
{
"version": "1.0.0.0",
"code": 200,
"message": "this is message",
"isError": false,
"data": {
"id": 1,
"name": "name",
"age": 21
}
}
================================
使用ApiResponse构造函数返回正常响应。
[Route("get1")]
[HttpGet]
public ApiResponse Get1()
{
var data = new { Id = 1, Name = "name", Age = 21 };
return new ApiResponse("this is message", data, StatusCodes.Status200OK);
}
异常响应
{
"version": "1.0.0.0",
"code": 500,
"isError": true,
"responseException": {
"exceptionMessage": "Unhandled Exception occurred. Unable to process the request."
}
}
================================
在接口层throw抛出异常
[Route("get1")]
[HttpGet]
public ApiResponse Get1()
{
try
{
int i = 0;
int j = 5 / i;
return new ApiResponse("New record has been created in the database", 1, StatusCodes.Status201Created);
}
catch (Exception ex)
{
throw;
}
}
==============================
使用ApiException抛出特定类型的异常。
[HttpGet]
[Route("get2")]
public ApiResponse Get2()
{
throw new ApiException("doesnt exist", StatusCodes.Status404NotFound);
}
入参字段不符合要求响应
{
"version": "1.0.0.0",
"code": 400,
"isError": true,
"responseException": {
"exceptionMessage": "Request responded with one or more validation errors occurred.",
"validationErrors": [
{
"name": "Name",
"reason": "最大长度5"
},
{
"name": "Location",
"reason": "最大长度5"
}
]
}
}
================================
使用ApiException抛模型错误异常。
[HttpPost]
[Route("customException")]
public ApiResponse Post1(AutoWrapperDemo model)
{
if(!ModelState.IsValid)
{
throw new ApiException(ModelState.AllErrors());
}
return new ApiResponse("New record has been created in the database", 1, StatusCodes.Status201Created);
}