Problems consuming REST by my App

0

Actually I did on the service side (which is working) I'm serializing a list, but in fact it's just a single value returned. For this service I have only one information, a decimal value, but I tried to put a simple Task and a FirstOrDefault return and give error. Well, I kept the List even though I know it's not the right way, but I'm going to change it. What I need right now is to make my Android App (Xamarin.Forms) consume this service. He's getting lost. By Postman okay, my REST is working, but by the App it does not work. See the codes in my App .

I made a model exactly as it is on the service side. This Model is exactly identical to the Model that is in REST, all.

public class DesvioFaturamento
    {
        public int IdUsuario { get; set; }
        public int IdGaragem { get; set; }
        public decimal Desvio { get; set; }
    }

There I made a class to deserialize what the service it provides

public class DataService
    {
        HttpClient client = new HttpClient();
        public async Task<List<DesvioFaturamento>> getDesvioFaturamento(int user, int garagem)
        {
            string url = $"http://localhost:2710/api/faturamento/{user}/{garagem}";
            var response = await client.GetStringAsync(url);
            var desvio = JsonConvert.DeserializeObject<List<DesvioFaturamento>>(response);
            return desvio;
        }
    }

And in my MainPage.xaml.cs I did the method (click) that takes what the service makes me like this:

try
            {
                if (!string.IsNullOrEmpty(txtUser.Text) && !string.IsNullOrEmpty(txtGaragem.Text))
                {
                    int user = Int32.Parse(txtUser.Text);
                    int garagem = Int32.Parse(txtGaragem.Text);
                    var data = await dataService.getDesvioFaturamento(user, garagem);
                    DesvioFatNotifications.Text = data.ToString();
                }
            }
            catch (Exception ex)
            {
                string erro = ex.Message;
            }

The var data ... is breaking. When it arrives at this point it does nothing and I need to close the debug, otherwise it is left without any response. Of course I did not wait more than 2 min, anyway, it does not work. How to consume this service?

EDIT1

Trying to solve this, I've put these lines in my project.

response.Wait(); // use assim ou com o while ....

                while (response.Status != System.Threading.Tasks.TaskStatus.RanToCompletion)
                {

                }

It is giving error that:

  

"string" does not contain a definition for Wait and was not found   "Wait" extension method ...

I have another App that I have no error on these lines and I have the same references and etc ...

EDIT2

My service is like this (Model):

[Route("faturamento/{iduser}/{idgaragem}")]
        public List<decimal> GetDesvioFaturamento(int iduser, int idgaragem)
        {
            var desvio = lista.Where(l => l.IdUsuario == iduser && l.IdGaragem == idgaragem)
                        .Select(s => s.Desvio).ToList();

            return desvio;
        }

My controller (ApiController)

[EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/Faturamento")]
    public class FaturamentoController : ApiController
    {
        DesvioFaturamentoModel desvio = new DesvioFaturamentoModel();

        [Route("{iduser}/{idgaragem}")]
        [AcceptVerbs("Get")]
        public IEnumerable<decimal> GetDesvioFaturamento(int iduser, int idgaragem)
        {
            return desvio.GetDesvioFaturamento(iduser, idgaragem);
        }
    }

My POCO class

public class DesvioFaturamento
    {
        public int IdUsuario { get; set; }
        public int IdGaragem { get; set; }
        public decimal Desvio { get; set; }
    }

EDIT3

EDIT4

Imadethisnewcode

try{HttpClientclient=newHttpClient();//client.BaseAddress=newUri("http://localhost:2710/api/");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.Timeout = TimeSpan.FromSeconds(60);

                //string url = $"faturamento/{user}/{garagem}";
                string url = $"http://localhost:2710/api/faturamento/{user}/{garagem}";
                var uri = new Uri(string.Format(url));

                try
                {
                    HttpResponseMessage response = await client.GetAsync(uri);


                    if (response.IsSuccessStatusCode)
                    {
                        var json = response.Content.ReadAsStringAsync();

                        return JsonConvert.DeserializeObject<List<DesvioFaturamento>>(json.Result);
                    }
                }
                catch (HttpRequestException ex)
                {
                    string erro = ex.Message;
                }

                return null;
            }
            catch (TaskCanceledException ex)
            {
                string erro = ex.Message;
                return null;
            }

and the HttpResponseMessage response = await client.GetAsync(uri); line is giving this error:

  

An error occurred while sending the request

pretty much says nothing

EDIT5

I have this code in my dataservice

try
            {
                client = new HttpClient();
                string url = $"http://localhost:2710/api/faturamento/{IdUsuario}/{IdGaragem}";
                try
                {
                    var response = await client.GetStringAsync(url);
                    var desvio = JsonConvert.DeserializeObject<List<DesvioFaturamento>>(response);
                    return desvio.ToList();
                }
                catch(Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

When it arrives at this line var response = await client.GetStringAsync(url); the app stops and I do not know what happens. It does not fall into the internal catch I put.

    
asked by anonymous 09.01.2018 / 12:58

1 answer

0

You have some missing details in the method that fetches the API data. I'll modify your method to the way I use it here and it works perfectly.

public async Task<List<DesvioFaturamento>> GetDesvioFaturamento(int user, int garagem)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:2710/api/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string url = $"faturamento/{user}/{garagem}";

    HttpResponseMessage response = await client.GetAsync(url);

    if (response.IsSuccessStatusCode)
    {
        var json = response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<List<DesvioFaturamento>>(json.Result);
    }

    return null;
}

Observations

  • Note that I use the BaseAddress property to set the base URL of your API. The way I was doing also works, but this is the recommended way (good practices) for this type of operation.

  • I added a header to your request: client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

Timeout

If you want, you can set a timeout for your request. To do this, simply add the following line under client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); :

client.Timeout = TimeSpan.FromSeconds(60);

After 60 seconds with no result, the method returns an exception of type TaskCanceledException .

public async Task<List<DesvioFaturamento>> GetDesvioFaturamento(int user, int garagem)
{
    try
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:2710/api/");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.Timeout = TimeSpan.FromSeconds(60);

        string url = $"faturamento/{user}/{garagem}";

        HttpResponseMessage response = await client.GetAsync(url);

        if (response.IsSuccessStatusCode)
        {
            var json = response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<List<DesvioFaturamento>>(json.Result);
        }

        return null;
     }
     catch(TaskCanceledException ex)
     {
        /// TODO
     }
}
    
09.01.2018 / 13:46