Forgive me for my ignorance, I am new to writing and consuming ASP.Net Core web APIs.
I have a web project that has an MVC architecture. The controllers call a web api to get data.
This is what I have so far:
using (var response = await _httpClient.GetAsync($"{_apiSettings.Value.BaseURL}/authors/{id}"))
{
if (response.IsSuccessStatusCode)
{
var apiResponse = await response.Content.ReadAsStringAsync();
var authorData = JsonSerializer.Deserialize<AuthorDTO>(apiResponse);
authorForm = _mapper.Map<AuthorViewModel>(authorData);
}
else
{
// What do I do here?
}
}
// more stuff down here to get to view...
As you can see I am not sure what should happen when I don't get a 200 code from the API call.
[Edit]
Is there a way to pass on the same HTTP response code? Is this a bad idea because that info shouldn't get to the user?
Is it best to just throw an error? If so should it always just be an Internal Server error?
I am just looking for advice on best practices, I realize there is no one right answer here.
CodePudding user response:
I think you can log the time, url, status code, response content and other info can help you. A Example From My Project
private static async Task<T> HandleHttpResponse<T>(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return JsonHelper.ToObject<T>(HandleHttpResult(result));
}
else
{
var result = await response.Content.ReadAsStringAsync();
LogHelper.WriteLog($"请求{response.RequestMessage.RequestUri}错误,错误描述:{response.StatusCode},错误码:{response.StatusCode.ToInt32()},错误内容:{result}", $"{nameof(RemoteServerHelper)}_{nameof(HandleHttpResponse)}", true);
}
return default;
}
CodePudding user response:
Well, there are several ways to return a request.
Example:
- System.Net.HttpStatusCode.Ok() (return status 200)
- System.Net.HttpStatusCode.BadRequest() (return status 400)
Here is the microsoft documentation:
https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.statuscode?view=net-6.0
