Failed with PostAsJsonAsync - WebApi - C #

0

I made a WebAPI that for Postman I can make a CRUD complete, but I created a Windows Forms C# pelo Visual Studio and I have some problems.

I can give get and all my data is fetched perfectly, but even giving a post , apparently gives a Ok 200 do methodo Post return, but nothing is created in my bank.

This is my controle :

public IHttpActionResult Post([FromBody]PROJETO projeto)
{
     var model = new ProjetoCriarEditarViewModel();
     model.CriarProjeto = _projetoBO.CriarProjeto(projeto);

     return Ok(model.CriarProjeto);
}

This is my method in C #.

private async void button1_Click(object sender, EventArgs e)
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:19832/");


        PROJETO project = new PROJETO();
        project.NOME = textBox1.Text;
        project.DATA_INICIO = dateTimePicker1.Value;
        project.DATA_PREVISTA = dateTimePicker2.Value;
        project.TECNOLOGIA = textBox2.Text;
        project.VALOR = Convert.ToDecimal(textBox3.Text);
        project.STATUS_PROJETO = textBox4.Text;
        project.ID_CLIENTE = Convert.ToInt32(textBox6.Text);


        var resposta = await client.PostAsJsonAsync("/api/projetos/", project);
        bool retorno = await resposta.Content.ReadAsAsync<bool>();
    }
}
    
asked by anonymous 23.02.2018 / 14:38

1 answer

0

I'll put an example of a method that I use in my projects and to this day it never gave me a headache. It's a bit different than yours, I think maybe these details make a difference.

private async Task<bool> PostoToAPIAsync(PROJETO projeto)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:19832/api/");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // Converte seu objeto para formato Json
    string json = JsonConvert.SerializeObject(projeto);

    // Espera o resultado
    HttpResponseMessage response = await client.PostAsync("projetos", new StringContent(json, Encoding.UTF8, "application/json"));

    // Verifica se o retorno é 200
    if (response.IsSuccessStatusCode)
    {
        return true;
    }

    return false;
}

Notice that I changed the address of your API and put a / at the end:

http://localhost:19832/api/

And I removed / from your API method:

projetos

Also, notice that the method I created is async , so you should call it as follows:

PROJETO project = new PROJETO();
project.NOME = textBox1.Text;
project.DATA_INICIO = dateTimePicker1.Value;
project.DATA_PREVISTA = dateTimePicker2.Value;
project.TECNOLOGIA = textBox2.Text;
project.VALOR = Convert.ToDecimal(textBox3.Text);
project.STATUS_PROJETO = textBox4.Text;
project.ID_CLIENTE = Convert.ToInt32(textBox6.Text);

if(await PostoToAPIAsync(project))
{
   // Criado com sucesso
}
else
{
   // Erro ao criar
}
    
23.02.2018 / 15:15