Problems consuming REST from my App

Asked

Viewed 791 times

2

In fact I did on the service side (which is working) I’m Automatically selecting a list, but in fact it’s just a single value returned. For that service I have only one information, one decimal value, but I tried to put one Task simple and a return Firstordefault and gives error. Well, so I kept the List even though it’s not the right way, but I’ll change it. What I need right now is to make my Android App(Xamarin.Forms) consume this service. It is getting lost. By Postman Okay, it’s working my REST, but by App is that it does not funfa. See the codes in my App.

I made a model exactly with is on the service side. This Model is exactly identical to Model which is in REST, everything.

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

Then I made a class to Deserialize what 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 made the Métod(click) that takes what the service makes available to 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 date... is breaking. When it gets to this point it does nothing and I need to close the debug, otherwise it is without any answer. Of course I didn’t wait more than 2 min, anyway, it doesn’t work. How to consume this service?

EDIT1

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

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

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

                }

Is making a mistake that:

"string" does not contain a definition for Wait and could not find any extension method "Wait"...

I have another app that I have no mistake in 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 class POCO

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

EDIT3 inserir a descrição da imagem aqui

EDIT4

I made this new code

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}";
                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 on the line of HttpResponseMessage response = await client.GetAsync(uri);is making that mistake:

An error occurred while sending the request

hardly says anything

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 you get on that line var response = await client.GetStringAsync(url); the app stops and no longer know what happens. It does not fall in the internal catch I put.

  • hehehe error is in your var deviation = list. Where(l => l.Idusuario == iduser && l.Idgarage == idgarage) . Select(s => s.Deviation). Tolist();

  • right here . Select(s => s.Deviation)

  • ai you make a deviation var = Jsonconvert.Deserializeobject<List<Deviation>>(Answer);

  • is what returns is a Deviation list and not the expected type or is List<Deviation>

  • see your own print that only has a 99 and not its class

  • So, I’ve been having this doubt since yesterday. What I need is to return only the expected value and I wasn’t getting it. Instead of returning a Ienumerable<decimal> should return to my class, right, @Marconciliosouza

  • I don’t know, it goes from your business rule, what you have to know is that you have to deserializeobject for the same kind you’re sending. If you are going to send a Embezzlement list you have to Deserializeobject to a list of the same type ...

  • What is returning in your var Response = await client.Getstringasync(url); ??? you will only need the Deviation

  • @Marconciliosouza, so I did this and it’s coming null my list. I made a change and when it comes to that line the system to: HttpResponseMessage response = await client.GetAsync(uri);

Show 4 more comments

1 answer

0

There are some details missing in the method that searches the API data. I will modify your method to the way I use 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;
}

Remarks

  • Note that I use the property BaseAddress to define the base URL of your API. The way I was doing it also works, but this is the recommended way (best 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 below client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));:

client.Timeout = TimeSpan.FromSeconds(60);

Once done, after 60 seconds with no result, the method will return a type exception 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
     }
}
  • When you get on that line HttpResponseMessage response = await client.GetAsync(url); for. I had this problem before and solved with the Wait() that I put in my edition and that now is not accepting and I do not know why.

  • Put the timeout as I said above and add a Try catch to the method and check if a timeout exception is generated. I updated the response.

  • Dude, when he gets on the line up for everything. It doesn’t lock, but nothing happens, like he’s lost. I will edit and post the service code, but I say testing by Postman I get the expected result.

  • Put a breakpoint on the if line (Answer.Issuccessstatuscode) and another breakpoint on catch(Taskcanceledexception ex) and see if the code gets there at least. And another, is the address used in Postman the same as the code? Your API is online at the specified localhost address?

  • The Postman is exactly as I am. The problem is that it doesn’t come in these lines. I’ve done it and it’s not enough. When it reaches the line quoted, it stops and does nothing else. I need to give a Kill. Postman URL copied and pasted: http://localhost:2710/api/billing/1/1

  • Could you place a Postman image? With the result and URL?

  • I put up a screenshot of Postman.

  • Take a look at the chat

Show 4 more comments

Browser other questions tagged

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