httpclient调用WebAPI

王朝学院·作者佚名  2016-08-28  
宽屏版  字体: 小 | 中 | 大 | 超大  

1、创建webapi项目,提供接口方法如下:

/// <summary>

/// 获取租户、位置下的所有传感器

/// </summary>

/// <returns></returns>

[AcceptVerbs("POST")]

[Route("api/Sensors/GetSensors")]

public JsonResponseBase<List<TenSensorDTO>> GetSensors()

{

Logger.Debug("SensorsController---------------GetSensors");

string jsonData = this.Request.Content.ReadAsStringAsync().Result;

Logger.Information(jsonData);

TenSensorSearchDTO search = null;

var response = new JsonResponseBase<List<TenSensorDTO>>();

try

{

search = JsonConvert.DeserializeObject<TenSensorSearchDTO>(jsonData);

response.Json.IsSuccess = true;

}

catch(Exception ex)

{

Logger.Fatal(ex);

response.Json.IsSuccess = false;

response.Json.OperationDesc = "参数错误";

}

if (response.Json.IsSuccess && search != null)

{

response = TenantManageService.GetSensorList(search);

}

return response;

}

2、客户端使用httpclient调用

string url = urlPRe + "Sensors/GetSensors";

//租户ID必须传入,LocationID可以不传入,看调用段需求

var content = new { TenantID = Guid.Parse("5ebf5f81-ac69-418c-b170-9eb255201dd1") ,

LocationID = Guid.Parse("db5a58c0-1d12-4fe9-99bb-4bebe6bcb935") };

var requestJson = JsonConvert.SerializeObject(content);

HttpContent httpContent = new StringContent(requestJson);

httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var httpClient = new HttpClient();

var responseJson = httpClient.PostAsync(url, httpContent)

.Result.Content.ReadAsStringAsync().Result;

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有