I am getting a strange error when calling an API from other API using Refit library.
FYI: My APIs are built using .Net 5.
The First API returns 200 response it is just the Refit which is unable to show the response.
I have checked the types of the response and model which are compatible.
First API
The declaration of the endpoint:
[Get("/projects/private/list")]
[Headers("Authorization: Bearer")]
Task<List<ProjectsResponse>> GetProjects([Body] ProjectsRequest projectIds);
The definition:
[HttpGet("private/list")]
[ProducesResponseType(statusCode: (int)HttpStatusCode.OK, type: typeof(IEnumerable<ProjectsResponse>))]
public async Task<IActionResult> GetProjects([FromBody] ProjectsRequest request)
{
IEnumerable<Project> projects = await _mediator.Send(new GetProjectsQuery { ProjectIds = request.ProjectIds });
return Ok(_mapper.Map<List<ProjectsResponse>>(projects));
}
The request model:
public class ProjectsRequest
{
public string[] ProjectIds { get; set; }
}
The response model:
public class ProjectsResponse
{
public string Id { get; set; }
public string Name { get; set; }
}
Second API
The call:
List<ProjectsResponse> projects = await _otherApi.GetProjects(new ProjectsRequest
{
ProjectIds = projectIds.ToArray()
});
Basically I am returning list of objects in the response which is causing this problem.
The strange behavior is that when I log the Request.Content
it works fine but when the log is removed the 502 error starts popping.
So, when I add _logger.LogInformation("Request:{data}", await request.Content.ReadAsStringAsync());
everything works correctly but when it is removed the Refit starts throwing 502.
I have done the token handling using the DelegatingHandler
of the Refit.
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var token = await GetAccessTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
//_logger.LogInformation("Request:{data}", await request.Content.ReadAsStringAsync());//Uncommenting this line makes it work.
HttpResponseMessage httpResponseMessage = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
//_logger.LogInformation("Response:{data}", await httpResponseMessage.Content.ReadAsStringAsync());
return httpResponseMessage;
}
catch (ApiException ex)
{
_logger.LogError(ex, ex.Message);
throw;
}
}