doubt to consume api

Asked

Viewed 114 times

-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 this way:

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 is not working, the application is simply aborted (without any warning) , does not fall into the debug of the Api, has something wrong in the code ?

I’m using C#

  • Hello, friend! Before trying to help you, to rule out any problems in that sense, is the API up and running? If yes, you can make explicit where your debug is stopped?

  • hello, this working yes, I modified the method to receive only one string, and tested with Postman, it worked right. Debug is interrponpid on this line: Httpresponsemessage Resp = await req.Postasync(url, stringContent);, here stops and does nothing else, does not arrive at the api, not from the error message, simply to.

  • Your var url and is set to what value after concatenation?

  • http://localhost:64785/Getvendas/save

2 answers

1


Got it. If you want it synchronously, you don’t need to call Wait(), just return Result directly. The result blocks the call thread until the task is completed. In this case, until the post is set, 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 a fake api and a console application to understand what was happening with your test.
Good luck.
I hope I’ve helped.

  • Well, it worked, but here comes a question, this service will be consumed by many customers, let’s say a thousand customers at the same time, while a customer is consuming the service, the other customers are in the queue (when it is not asynchronous), right? this would not generate a team out?

  • OPA, I made confusion, the api method that has to be asynchronous. Thanks for the help

0

Hello, friend! Your API is in an X url and you need to make it clear 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’ve helped.
Hugs,

  • I tried as you suggested, but for this line Aki: var result = await req.Postasync("/Getsales/save", content); //, does not arrive at api, does nothing.

  • I believe your route is wrong. The post should be performed on top of a valid route. Example: https://localhost:5000/api/users passing a formatted content to it. I believe your route has some error. What is your entire route or which route you are planning to reach? You can tell us which address you tested on Postman?

  • I used it like this in Postman: http://localhost:64785/Getsales/Save? sale=sdasd, worked (remembering q for this test I changed save method to receive only one string, )

  • Can you include the route specified in your api controller? Example: [Route("api/[controller]")]&#xA; [ApiController]

Browser other questions tagged

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