Httpclient calls WebAPI, httpclientwebapi

Source: Internet
Author: User

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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.