How to pass Json parameters, to consume a C#API

Asked

Viewed 1,174 times

0

I am trying to consume a Pay API transfer that asks to be passed the email of who will receive, the value and the description, I did according to the model below but I think it is not correct.

Note: I deleted my token and email in the API url.

public ActionResult FazerTransferencias()
{
    var uri = "https://ws.pagseguro.uol.com.br/transfer/authorize?email=&token=";
    WebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "POST";
    request.ContentType = "application/json";

    string receiverEmail = "[email protected]";
    string amount = "1.00";
    string description = "Transferência How2Code";

    String input = "{\"receiverEmail\":\"" + receiverEmail + "\",\"amount\":\"" + amount + "\",\"description\":\"" + description + "\"} ";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(input);
        streamWriter.Flush();
        streamWriter.Close();

        var httpResponse = (HttpWebResponse)request.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return Json("Retornou");
        }
    }

API documentation: https://dev.pagseguro.uol.com.br/#requesting authorization-1

when debugging the code the api returns the error 500.

detail in the account has no money this serious error for this reason, or is some error in the same code.

  • error on which line? I see a problem there in your code: StreamReader should be opened after using the StreamWriter

  • The error appears on this line var httpResponse = (Httpwebresponse)request.Getresponse(); after Streamwriter.Close();

  • tried to put this after finishing the Streamreader?

  • And what is the description of error 500?

1 answer

0


Try to do something like that. It’s simpler and it should work:

public string FazerTransferencias()
{
    var data = new
    {
        receiverEmail = "[email protected]",
        amount = 1,
        description = "Transferência How2Code"
    };

    string email = "[email protected]";
    string token = "12345";
    var result = new HttpClient().PostAsJsonAsync($"https://ws.pagseguro.uol.com.br/transfer/authorize?email={email}&token={token}", data).Result;
    return result.Content.ReadAsAsync<string>().Result;
}

Browser other questions tagged

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