How to use POST in a json for an Http server

1

I was wondering how can I do a POST from a json to an http server. The code I am using to do json is as follows:

Person person= new Person();
                    product.FirtsName = "Ola";
                    product.ID = 1;
                    product.age= 10;


                    string json = JsonConvert.SerializeObject(product);

And this is the class Person :

 public class Person
    {
        public int ID { get; set; }
        public string FirtsName { get; set; }
        public int age { get; set; }
    }
    
asked by anonymous 24.08.2017 / 12:10

1 answer

2

First, I'm going to change its class Pedro , to a class called Pessoa and sort nomenclatures. Decide whether to use properties in English or Portuguese. In this case, I'll use the properties in English:

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public int Age{ get; set; }
}

Adjusted this, you need an asynchronous method and a HttpClient object. In this case I opted to return a bool if the operation returns a success code:

/// <summary>
/// Cria uma pessoa
/// </summary>
/// <param name="person">Objeto 'Person'</param>
/// <returns></returns>
private async Task<bool> CreatePersonAsync(Person person)
{
    var client = new HttpClient();
    client.BaseAddress = new Uri("endreço da sua web api");
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    // Transforma o objeto em json
    string json = JsonConvert.SerializeObject(person);

    // Envia o json para a API e verifica se obteve sucesso
    HttpResponseMessage response = await client.PostAsync("Controller da sua API para criar a pessoa", new StringContent(json, Encoding.UTF8, "application/json"));
    response.EnsureSuccessStatusCode();

    if (response.IsSuccessStatusCode)
    {
       return true;
    }

    return false;
}
  

Note that in "api web remit" is the http address of your API.

For example: link

  

Note that in "Controller of your API to create the person" is just the   name of the Controller responsible for creating the "person" (Person object).

For example: if within your API the Controller responsible for creating people is called "Person", it is the name that will be placed.

Using the

To call this method and wait for the result, you can do the following:

// Método para criar a pessoa e enviar para a Web API
public async void CreatePerson()
{
   // Cria um objeto "Person"
   var person = new Person()
   {
       ID = 1,
       FirstName = "Pedro",
       Age = 10
    }

    // Cria a pessoa e armazena o resultado
    var isOK = await CreatePersonAsync(person);

    // Verifica se obteve sucesso
    if(isOK)
    {
        // Pessoa criada com sucesso
    }
}
  

Note that the method must be async , because inside it we will call the   method async we created earlier to create the person on the web   API. In addition, we use the await directive to wait for the method   execute and return.

    
24.08.2017 / 13:23