gpt4 book ai didi

c# - 如何从 Web API 接收这个 Json?

转载 作者:行者123 更新时间:2023-11-30 23:22:56 28 4
gpt4 key购买 nike

我有这个结构..

客户端 <-> Web Api 前端 <-> Web Api 返回 -> 数据库

因此,当我的 Web Api 返回向我发送 Json 时,我不知道如何获得结果。

我没有显示与数据库的连接。

在 Web Api Front 上,行 var data = response.Content.ReadAsStringAsync().Result; 为我提供了具有所有正确值的 Json 数组。但我不知道如何将其发送到客户端的 ApiCall。

我必须在返回上填写什么?

[调用 Web Api 前端的服务]

public class ApiCall
{
static readonly string ApiUrl = "http://Localhost:1762/api/{0}/{1}?nomePesquisa={2}&nomeMae={3}&nomePai={4}&dtNasc={5}&nrg={6}&ncpf={7}";


//buscar os dados com os parametros digitados
public async Task<T> GetResponse<T>(string controller, string method, string nomepesquisa,
string nomemae, string nomepai, string dtnasc, string nrg, string ncpf) where T : class
{
var client = new System.Net.Http.HttpClient();

//Definide o Header de resultado para JSON, para evitar que seja retornado um HTML ou XML
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var urllink = string.Format(ApiUrl, controller, method, nomepesquisa, nomemae, nomepai, dtnasc, nrg, ncpf);
var response = await client.GetAsync(urllink);

//Lê a string retornada
var JsonResult = response.Content.ReadAsStringAsync().Result;

if (typeof(T) == typeof(string))
return null;

//Converte o resultado Json para uma Classe utilizando as Libs do Newtonsoft.Json
var rootobject = JsonConvert.DeserializeObject<T>(JsonResult);
return rootobject;
}

}

[Web Api 前端调用 Web Api 返回]

[HttpGet]
[Route("Envolvidos")]
public IEnumerable<Envolvido> GetEnvolv(string nomePesquisa, string nomeMae, string nomePai, string dtNasc
, string nRG, string nCPF)
{

DataSet lretorno = new DataSet();

using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://Localhost:1762/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

// Usage
HttpResponseMessage response = client.GetAsync("api/nomes/Envolvidos?nomePesquisa="+nomePesquisa+"&nomeMae="+nomeMae+"&nomePai="+nomePai+"&dtNasc="+dtNasc+"&nrg="+nRG+"&ncpf="+nCPF+"").Result;

if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync().Result;
//Envolvido envolvidoResult = JsonConvert.DeserializeObject<Envolvido>(data);
return data.AsEnumerable().Select(row => new Envolvido
{

});

}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}


//return WHATTTTT?? ;

}

}

[WebApi 返回]

[HttpGet]
[Route("Envolvidos")]
public IEnumerable<Envolvido> GetEnvolv(string nomePesquisa, string nomeMae, string nomePai, string dtnasc
, string nRG, string nCPF)
{

DataSet lretorno = new DataSet();

string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;

OracleDataReader reader = null;
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd = new OracleCommand("MOBILE.XAPIMANDADOMOBILE.BUSCAPOSSIVEISCANDIDATOSPF", connection);
cmd.CommandType = CommandType.StoredProcedure;

//variáveis entrada
cmd.Parameters.Add(new OracleParameter("ivnome",nomePesquisa));
cmd.Parameters.Add(new OracleParameter("ivmae", nomeMae));
cmd.Parameters.Add(new OracleParameter("ivpai", nomePai));
cmd.Parameters.Add(new OracleParameter("ivdatanasc", dtnasc));
cmd.Parameters.Add(new OracleParameter("ivrg", nRG));
cmd.Parameters.Add(new OracleParameter("icpf", nCPF));
//variáveis de saida
cmd.Parameters.Add(new OracleParameter("oretorno", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;
cmd.Parameters.Add(new OracleParameter("qretorno", OracleDbType.RefCursor)).Direction = ParameterDirection.Output;

connection.Open();
cmd.ExecuteNonQuery();

reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

//CRIO A LISTA
lretorno.Load(reader, LoadOption.OverwriteChanges, "BUSCAPOSSIVEISCANDIDATOSPF");
connection.Close();
connection.Dispose();


//CARREGO O DATASET E TRANSFORMO PARA IENUMERABLE E RETORNO SEUS VALORES PRO JSON
return lretorno.Tables[0].AsEnumerable().Select(row => new Envolvido
{
SUSPID = Convert.ToInt32(row["SUSPID"]),
IVNOME = Convert.ToString(row["SUSPNOME"]),
IVMAE = Convert.ToString(row["SUSPMAE"]),
IVPAI = Convert.ToString(row["SUSPPAI"]),
IVDATANASC = Convert.ToString(row["SUSPDATANASC"]).Replace(" 00:00:00", ""),
IVRG = Convert.ToString(row["RG"]),
ICPF = Convert.ToString(row["CPF"]),
MANDADO = Convert.ToInt16(row["TEMMANDADO"]),
OCORRENCIA = Convert.ToInt16(row["TEMOCORRENCIA"]),

});


}
}

最佳答案

Web API 后端正在返回 IEnumerable<Envolvido>

当 Web Api 前端调用 Web Api 后端时,它只需要将其反序列化为可分配给 IEnumerable<Envolvido> 的内容即可。 , 无论是列表、集合、数组...等等

//...other code removed for brevity
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsAsync<List<Envolvido>>().Result;
return data;
}
//...other code removed for brevity

关于c# - 如何从 Web API 接收这个 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38599298/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com