1
Friends,
I always try to focus on good programming practices, and one practice that most confuses me is the Modularization. For example, I have the method below that receives data from an API and sends to View this collection. Well, in this method some different functions are exercised, and the need to modularize is clear. However, I am confused about how each part should be modularized:
//String da API que eu conecto.
string baseUrl = "http://endereco.com.br/api/";
public async Task<ActionResult> Index()
{
List<employee> employee = new List<employee>();
//Cria um HTTPClient e atribui determinados parâmetros para a conexão
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage message = await client.GetAsync("employee");
if (message.IsSuccessStatusCode)
{
//Se tudo der certo, ele vai atribuir o resulto à "response" e desserializar para JSON.
var response = message.Content.ReadAsStringAsync().Result;
employee = JsonConvert.DeserializeObject<List<employee>>(response);
}
return View(employee);
}
}
I thought, for example, to create a specific method for creating and assigning Httpclient. However it could not stay in this controller, since it is being used to access the pages.
In the experience of friends, how should we divide the code of this method?
Perfect, buddy! That’s exactly what I was looking for. Just one modification, my signature was: "public async Task<T> Get<T>(string endpoint)", so I can use this method for whatever Get I’m going to do. Thank you!
– Csorgo
An extra tip, if the project is large-scale, deploy the architecture in layers.
– HudsonPH