如何从Web API接收此Json
本文关键字:Json API Web | 更新日期: 2023-09-27 17:58:59
我有这个结构。。
客户端<->Web Api前端<->Web Api返回->数据库
所以,当我的网络Api Back给我发送Json时,我不知道如何得到结果。
我没有显示与数据库的连接。
在Web Api Front上,var data = response.Content.ReadAsStringAsync().Result;
行为我提供了具有所有正确值的Json数组。但我不知道如何将其发送到客户端的ApiCall。
我必须在退货单上写些什么?
【调用Web Api Front的服务】
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>
的东西,无论是List、Collection、Array。。。etc
//...other code removed for brevity
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsAsync<List<Envolvido>>().Result;
return data;
}
//...other code removed for brevity