Postasjsonasync Failure - Webapi - C#

Asked

Viewed 1,121 times

2

I made a WebAPI that by Postman I can make a CRUD but I created a Windows Forms C# pelo Visual Studio and I’m having some problems.

I can give a get and all my data is searched perfectly, only that while giving a post, apparently of a return Ok 200 do methodo Post, 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 C method#.

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>();
    }
}
  • just to be sure, your _projetoBO.CriarProjeto is giving commit at the end of the process?

  • Yes. I can post by Postman using the api and it creates perfectly in the database of my application. And I can also use "_projectBO.Criar projeto" in every app.

  • 1

    Put the [Httppost] attribute on top of your Controller?

  • 1

    I did not put it because he understands that it is a Post by the name of the method. So in this case it makes no difference.

  • @joaop.mr But did you test with the attribute? Do the post with the attribute through the code and not from Postman?

  • I tested for rs and nothing.

  • if already debugged? another thing inside this code: Create project?

  • I have debugged it. It returns the OK 200 post method. As if it had saved it. However it does not save.

  • Creating project is my method in the business rules that leads to the repository. Otherwise, I use the Entity Framework.

  • You have to debug the code from the repository!

  • But I can send by Postman. And I can also save in the application. I will anyway.

Show 6 more comments

1 answer

1

I will put an example of the method I use in my projects and to this day never gave me a headache. It’s a little different than yours, I think maybe these details will 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;
}

Note that I changed the address of your API and put a / in the end:

http://localhost:19832/api/

And I removed the / of your API method:

projetos

Also, understand that the method I’ve created is async, then 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
}
  • Thanks for the tip. I did exactly that friend. I continue with the same problem. It returns success but does not record anything in the bank.

Browser other questions tagged

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