1

I have this api in php that works ok when sending data from an html form.

<?php

include_once 'apiAppMovil.php';

$api = new AppMovil();
$error = '';

if(isset($_POST["nombre"]) && isset($_POST["ape"]) && isset($_POST["email"]) && isset($_POST["pass"])){

    if($api->subirImagen($_FILES['foto'])){
        $item = array(
            "nombre" => $_POST["nombre"],
            "ape" => $_POST["ape"],
            "email" => $_POST["email"],
            "pass" => $_POST["pass"],
            "foto" => $api->getImagen() //Not used
        );
        
        $api->add($item);
    }else{
        $api->error('Error con el archivo: ' . $api->getError());
    }
}
else{
    $api->error('Error al llamar a la API');
}

?>

I want to send data but from c#. My class is the following:

public partial class Root
{
    [JsonProperty("items")]
    public Item[] Items { get; set; }
}

public partial class Item
{/*
    [JsonProperty("id")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long Id { get; set; }*/

    [JsonProperty("nombre")]
    public string Nombre { get; set; }

    [JsonProperty("ape")]
    public string Ape { get; set; }

    [JsonProperty("email")]
    public string Email { get; set; }

    [JsonProperty("pass")]
    public string Pass { get; set; }

    [JsonProperty("foto")] //Not Used
    public string Foto { get; set; }
}

and my method is:

private async Task SignUpApiPost()
    {
        var data = new Item
        {
            Nombre = "Eric",
            Ape = "Pino",
            Pass = "M2022",
            Email = "ericpinodiaz@gmail.com",
            Foto = "default.jpeg" //Not Used
        };

        // Serialize our concrete class into a JSON String
        var json = JsonConvert.SerializeObject(data);

        // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
        var httpContent = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

        var httpClient = new HttpClient();

        // Do the actual request and await the response
        var response = await httpClient.PostAsync("https://app.domainexample.com/rest/add.php", httpContent);
                    
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
             //do thing             
        }
    }

But I can't get the data to arrive, I have the errors "Error al llamar a la API" from Api php. I think the problem is that var data = new Item{ is not declared correctly, can you help me and tell me where I am going wrong?

Thank you.

Edit:

I add the html with which it works correctly:

enter image description here

Fran Pino
  • 111
  • 7
  • Use a sniffer and compare the working php request with the c# request. Make c# request look exactly like working php. The default http headers in c# are different from php. Usually getting modifying the c# header solve issue. – jdweng Jun 08 '22 at 17:23
  • You are passing foto property as a string, not as a file. Can you remove $_FILES from "foto" in php code and change it same as other properties and check? – shehanpathi Jun 08 '22 at 17:35
  • I have eliminated $_FILES["photo"] to rule out a possible problem but it is still the same, it returns a Null at the end – Fran Pino Jun 14 '22 at 08:06
  • I edit my question and add the html with which it works correctly. – Fran Pino Jun 14 '22 at 08:17
  • 1
    The header that specifies the content type of your http content is `string[]` (the default), which causes PHP to try and interpret the body as a string array. try setting the request content type to `text/json`. see : https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c dotnetfiddle that shows what i am talking about : https://dotnetfiddle.net/IIZhMG – Timothy Groote Jun 14 '22 at 08:33
  • And how can I solve it? what should I do? – Fran Pino Jun 15 '22 at 11:18

1 Answers1

1

You should try something like the one below.

client.BaseAddress = new Uri("your url");

//HTTP POST
var postTask = client.PostAsJsonAsync<StudentViewModel>("your  parameter name",    Item);
        postTask.Wait();

        var result = postTask.Result;
        if (result.IsSuccessStatusCode)
        {
            //do something
        }
Jalpesh Vadgama
  • 13,653
  • 19
  • 72
  • 94
  • I have tried this code, it returns StatusCode 200, but I do not create the record in my table: var postTask = client.PostAsJsonAsync(client.BaseAddress, data); – Fran Pino Jun 15 '22 at 15:04
  • 1
    that is problem with the api then check your api – Jalpesh Vadgama Jun 16 '22 at 07:07
  • my api save record in table like this: function nuevoUsuario($usuario){ $query = $this->connect()->prepare('INSERT INTO usuarios (nombre) VALUES (:nombre)'); $query->execute(['nombre' => $usuario['nombre'] ); return $query; } I have modified the API so that it only adds the NAME – Fran Pino Jun 16 '22 at 11:15
  • Sorry, I am not a PHP guy so don't know much about it. But check your models and see if you are getting your models correctly. – Jalpesh Vadgama Jun 16 '22 at 11:19