[英]Describing Dynamic Response Types For REST API
我為所有REST API使用標准的APIResponse對象接口。
public interface IAPIResponse
{
IAPIError Error { get; set; }
IEnumerable<dynamic> Results { get; set; }
void AddResult(string groupName, object data);
}
這是我使用標准APIResponse對象的方式。
public async Task<IActionResult> Get()
{
try
{
var response = new UsersGetResponse {
Users = await _someService.GetAll()};
_apiResponse.AddResult("UsersGetResponse", response );
return new ObjectResult(_apiResponse);
}
catch (Exception ex)
{
_apiResponse.Error = new APIError(ex.Message, 500);
return new ObjectResult(_apiResponse);
}
}
_someSerice.GetAll()的調用返回以下用戶對象的列表。
public interface IUser
{
string Id { get; set; }
bool IsAdmin { get; }
string Name { get; set; }
string Email { get; set; }
}
這是父類UsersGetResponse的屬性
public class UsersGetResponse
{
public IList<User> Users { get; set;}
}
這將產生以下JSON。
{
"error": null,
"results": [
{
"UsersGetResponse": {
"Users": [
{
"id": 171161,
"isAdmin" : true,
"name": "Dave Smith",
"email": "Dave.Smith@gmail.com"
},
{
"id": 171162,
"isAdmin" : false,
"name": "Jane Doe",
"email": "Jane.Doe@gmail.com"
}
]
}
}
]
}
如果我像這樣使用ProducedResponseType批注。
[ProducesResponseType(typeof(IAPIResponse), StatusCodes.Status200OK)]
我只能大張旗鼓地獲得以下示例JSON。
{
"error": {
"message": "string",
"number": 0
},
"results": [
{}
]
}
我正在嘗試查看是否有一種方法可以正確地與我的API使用者進行通信,我有一個標准的APIResponse對象,並且具有帶有特定結果(例如UsersGetResponse)的動態結果。
這是因為您正在使用動態類型。 Swagger無法識別該類型的任何“屬性”。 如果您改用具體類型或接口,則swagger將為您顯示該對象的屬性。
如果不完全了解您要做什么的范圍,我將無法為您提供完整的解決方案。 但是,使用提供的信息,這是您應該做的:
public sealed class APIResponse<T>
{
IAPIError Error { get; set; }
T Results { get; set; }
}
public async Task<IActionResult> Get()
{
var response = new ApiResponse<<IEnumerable<User>>>();
try
{
var data = await _someService.GetAll();
response.Result = data;
return Ok(response);//returns 200 status code
}
catch (Exception ex)
{
response.Error = new APIError(ex.Message, 500);
return BadRequrest(response);
}
}
然后,您可以像這樣注釋:
[ProducesResponseType(typeof(APIResponse<IEnumerable<User>>), StatusCodes.Status200OK)]
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.