簡體   English   中英

在 C# 中將發布數據發送到 api

[英]Send post data to api in C#

我在 php 中有這個 api,它在從 html 表單發送數據時可以正常工作。

<?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');
}

?>

我想從 c# 發送數據。 我的班級如下:

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; }
}

我的方法是:

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             
        }
    }

但我無法讓數據到達,我有來自 Api php 的錯誤“Error al llamar a la API” 我認為問題是var data = new Item{沒有正確聲明,你能幫我告訴我哪里出錯了嗎?

謝謝你。

編輯:

我添加了它可以正常工作的html:

在此處輸入圖像描述

您應該嘗試以下類似的方法。

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
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM