doubt to consume api

-1

I have the following service:

[HttpGet]
    [Route("save")]
    public async Task<dynamic> save(VendaModel[] venda, string CnpjEstab)
    {
        dynamic retorno = null;
        VendaModel ultima = new VendaModel();

       //TODO   
    }

I'm trying to consume as follows:

public async static void SalvarArray(dynamic venda, string CnpjEstab)
    {
        string retorno;
        try
        {
            var url = UrlBase.urlBase + "/GetVendas/save";
            var a = new { venda, CnpjEstab };
            var json = JsonConvert.SerializeObject(a);

            var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

            HttpClient req = new HttpClient();
            HttpResponseMessage resp = await req.PostAsync(url, stringContent);

            if (resp.StatusCode == HttpStatusCode.OK)
            {
                retorno = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            }
        }
        catch (Exception err)
        {
            GeraLogError.GeraLog("GetVendas", MethodBase.GetCurrentMethod().Name, err.Message);
            retorno = err.Message;
        }

        //return retorno;
    }

But it's not working, the application is simply aborted (without any warning), does not fall into the Api debug, is there something wrong with the code?

I'm using C #

    
asked by anonymous 01.12.2018 / 18:03

2 answers

1

I understood. If you want to synchronize, you do not have to call wait (), just return Result directly. The result locks the calling thread until the task completes. In this case, until the post is defined, you can use it as follows:

var serializedVendas = JsonConvert.SerializeObject(data);
var content = new StringContent(serializedVendas, Encoding.UTF8, "application/json");
var result = client.PostAsync ("api/vendas", content).Result;

I just tested with an example application and it worked. I had to create an api fake and console application to understand what was going on with your test. Good luck. I hope I have helped.

    
01.12.2018 / 20:51
0

Hello, my friend! Your API is in an X url and you need to spell it out in the code. Example:

req.BaseAddress = new Uri("http://localhost:5000/"); //para uma api com esse caminho.
req.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json")
            );
var serializedVendas = JsonConvert.SerializeObject(data);
var content = new StringContent(serializedVendas, Encoding.UTF8, "application/json");
var result = await req.PostAsync("api/vendas", content); //caso essa seja sua rota


I hope I have helped.
Hugs,

    
01.12.2018 / 18:48