ASP.NET MVC 5 refactoring method to consume api

0

I am at a crossroads, since I am developing a web app where I must consume an api by GET and POST, the logic of the service is solved, but I would like to refactor the code so that I do not have to repeat the same pieces in each request.

I have something like the following:

Controller

public async Task<ActionResult> Index()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://192.168.0.1:1000/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token");

            // GET Method
            HttpResponseMessage HttpResponseMessage = await client.GetAsync("api/url");

            MiModelo model = new MiModelo();
            if (HttpResponseMessage.IsSuccessStatusCode)
            {
                var EmpResponse = HttpResponseMessage.Content.ReadAsStringAsync().Result;
                model = JsonConvert.DeserializeObject<model >(EmpResponse);
            }

            return View(model );
        }
    }

What I want to get to is something like this - > link but I could not , it would be great if someone knows, so that he shares his knowledge and hopefully he can serve someone else.

    
asked by vcasas 03.05.2018 в 18:40
source

1 answer

0

A simple refactor can be done this way:

public async Task<ActionResult> Index()
{
    var objhttp = new HttpClientHelper();

    using (var client = objhttp.GenerateClient())
    {
        // GET Method
        HttpResponseMessage HttpResponseMessage = await client.GetAsync("api/url");

        MiModelo model = new MiModelo();
        if (HttpResponseMessage.IsSuccessStatusCode)
        {
            var EmpResponse = HttpResponseMessage.Content.ReadAsStringAsync().Result;
            model = JsonConvert.DeserializeObject<model>(EmpResponse);
        }

        return View(model);
    }
}  

Create a Helper class, if you prefer it can be static

public class HttpClientHelper
{
    public HttpClient GenerateClient()
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("http://192.168.0.1:1000/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token");
        return client;
    }
}
    
answered by 03.05.2018 / 19:03
source