Httpclient calls WebAPI, httpclientwebapi
1. Create a webapi project and provide the following interface methods:
/// <Summary>
/// Obtain all the sensors in the tenant and location
/// </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 = "parameter error ";
}
If (response. Json. IsSuccess & search! = Null)
{
Response = TenantManageService. GetSensorList (search );
}
Return response;
}
2. The client uses httpclient to call
String url = urlPre + "Sensors/GetSensors ";
// The Tenant ID must be passed in, and the LocationID can be left blank.
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;