C# 请求Web Api 接口,返回的json数据直接反序列化为实体类

时间:2024-01-09 22:05:50

须要的引用的dll类:

Newtonsoft.Json.dll、System.Net.Http.dll、System.Net.Http.Formatting.dll



Web Api接口为GET形式:

 public static CstyleCmappListRespDTO GetCstyleCmappList(string cstylename, string cmappgname)
{
CstyleCmappListRespDTO RespDTO = new CstyleCmappListRespDTO();
var url = string.Empty;
try
{
url = RequestUrl + "/dw/get_cstylecmappg_info_dw? id={0}&key={1}×tamp={2}&cstylename={3}&cmappgname={4}";
url = string.Format(url, id, key, DateTime.Now.ToString("yyyyMMddHHmmss"), cstylename, cmappgname);
var httpClient = new HttpClient();
HttpResponseMessage response = httpClient.GetAsync(new Uri(url)).Result;
RespDTO = response.Content.ReadAsAsync<CstyleCmappListRespDTO>().Result;
}
catch (Exception ex)
{ }
return RespDTO;
}

Web Api接口为POST形式:

public static FlightsResponse QueryFlightPost(FlightQueryRequest ReqDTO)
{
FlightsResponse FlightsRespDTO = new FlightsResponse();
try
{
string requestDTO = JsonConvert.SerializeObject(ReqDTO);
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent httpContent = new ObjectContent<FlightQueryRequest>(ReqDTO, jsonFormatter);
var url = RequestUrl + "/QueryFlight";
var httpClient = new HttpClient(new RequestHandler() { InnerHandler = new HttpClientHandler() });
httpClient.Timeout = TimeSpan.FromMinutes(3);
var responseJson = httpClient.PostAsync(url, httpContent).Result;
FlightsRespDTO = responseJson.Content.ReadAsAsync<FlightsResponse>().Result; }
catch (Exception)
{
FlightsRespDTO = new FlightsResponse();
}
return FlightsRespDTO;
}