POST is not receiving JSON

Asked

Viewed 830 times

1

I need some help with running a POST. 'Cause when I try to call my API (http://www.afectus.com.br/api/teste) for the execution of a Post, I am unable to pass the JSON to her.

Follows the API used:

// POST: api/Teste
public void Post([FromBody]string json)
{
    ClassRetorno cr = new ClassRetorno();

    if (string.IsNullOrEmpty(json))
    {
        cr = JsonConvert.DeserializeObject<ClassRetorno>("{\"Id\":1,\"Nome\":\"From Api\",\"Email\":\"[email protected]\"}");
    }
    else
    {
        cr = JsonConvert.DeserializeObject<ClassRetorno>(json);
    }

     mysql = new ClassMySQL();
     if (mysql.conectar())
     {
         mysql.insert("teste", "id, nome, email", cr.Id + ",'" + cr.Nome + "','" + cr.Email + "'");
     }
}

Summarizing: If the Json string is null or empty, it will be saved in the database (Id: 1, Name: From Api, Email: [email protected])

If not, it will be saved as per the received parameter.

This is the method that executes the Post:

public async Task Posting(ClassRetorno item)
{
    using (var client = new HttpClient())
    {
        var uri = new Uri("http://www.afectus.com.br/api/teste");
        var json = JsonConvert.SerializeObject(item);
        var content = new StringContent(json, Encoding.UTF8, "text/json");
        HttpResponseMessage response = new HttpResponseMessage();
        response = await client.PostAsync(uri, content);
        if (response.IsSuccessStatusCode)
        {
            await DisplayAlert("Alert", "Post executado!", "Ok");
        }
        else
        {
            await DisplayAlert("Alert", "Post não executado!", "Ok");
        }
    }
}

If anyone knows the possible cause of this problem, or at least can give some guidance, I would be grateful.

Obs: I used the Postman tool to test the API and it still didn’t work.

  • It was not clear in the question what exactly did not work. Is there an error? Where?

  • You forgot to tell me what the problem is...

  • Okay, thank you. It’s just that when I try to call my api by passing a json to it. It’s like it doesn’t get that json.

1 answer

1


Receive the object ClassRetorno as a parameter instead of [FromBody]string json, the ModelBindingwill solve the json that is coming.

  • Thank you very much Lucas. I confess that I tried to remove only the [Frombody], leaving string json, because he imagined that the post needed to necessarily receive a string.

  • I had a similar problem, I put only the object I would like to receive and the aspnet modelbinding solved the Json that was coming

Browser other questions tagged

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