Doubt about modularization in MVC Application

Asked

Viewed 109 times

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?

1 answer

2


In good practice the best would be that this part stays within a service, and it shaped in a Generic way.

public async Task<List<T>> ListaAsync(){
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(typeof(T).Name);
            if (message.IsSuccessStatusCode)
            {
                //Se tudo der certo, ele vai atribuir o resulto à "response" e desserializar para JSON.
                var response = message.Content.ReadAsStringAsync().Result;
                return = JsonConvert.DeserializeObject<List<T>>(response);
            } else {
           return T = new List<T>();
           }
        }
}

I don’t know how you put it to base, but in good practice the best would be within the Web.config, because if Voce needs to change the Voce url it can direct to the hosting site.

 <appSettings>
    <add key="baseUrl" value="http://endereco.com.br/api/"/>
  </appSettings>

C#

string baseUrl = ConfigurationManager.AppSettings["baseUrl"]
  • 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!

  • An extra tip, if the project is large-scale, deploy the architecture in layers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.