【发布时间】:2022-06-14 16:16:59
【问题描述】:
我在 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"]) && isset($_FILES["foto"])){
if($api->subirImagen($_FILES['foto'])){
$item = array(
"nombre" => $_POST["nombre"],
"ape" => $_POST["ape"],
"email" => $_POST["email"],
"pass" => $_POST["pass"],
"foto" => $api->getImagen()
);
$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")]
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"
};
// 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:
【问题讨论】:
-
使用嗅探器并将工作的 php 请求与 c# 请求进行比较。使 c# 请求看起来与工作 php 完全一样。 c# 中的默认 http 标头与 php 不同。通常修改 c# 标头可以解决问题。
-
您将 foto 属性作为字符串而不是文件传递。您可以从 php 代码中的“foto”中删除 $_FILES 并将其更改为与其他属性相同并检查吗?
-
我已经消除了 $_FILES["photo"] 以排除可能的问题,但它仍然是一样的,它在最后返回一个 Null
-
我编辑了我的问题并添加了可以正常工作的 html。