Use HttpClient to consume ASP. NET Web API service, httpclientasp.net
This article uses HttpClient to consume ASP. NET Web API services. The example is relatively simple.
Click "file", "new", and "project" in turn ".
Select the "ASP. NET Web API" project.
Create the Person. cs class in the Models folder.
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Create an empty PersonController In the Controllers folder.
public class PersonController : ApiController
{
}
Create a method that complies with the management, GetAllPersons.
public class PersonController : ApiController
{
public IEnumerable<Person> GetAllPersons()
{
return new List<Person>
{
new Person(){Id = 1, FirstName = "jack", LastName = "li"},
new Person(){Id = 2, FirstName = "darren", LastName = "ji"},
new Person(){Id = 3, FirstName = "sunny", LastName = "su"}
};
}
}
Enter:
Http: // localhost: 2497/api/Person
Http: // localhost: 2497/api/Person/AllPersons
Data can be obtained.
Create a console application under the solution.
Reference System. Net in the console and write the following code:
static void Main(string[] args)
{
using (WebClient proxy = new WebClient())
{
var response = proxy.DownloadString("http://localhost:2497/api/Person");
Console.WriteLine(response);
Console.ReadKey();
}
}
Set the console program as the startup Item. Click "start ".
To obtain the xml format, you can set the Headers attribute of WebClient.
The code is modified as follows:
static void Main(string[] args)
{
using (WebClient proxy = new WebClient())
{
proxy.Headers.Add(HttpRequestHeader.Accept, "application/xml");
var response = proxy.DownloadString("http://localhost:2497/api/Person");
Console.WriteLine(response);
Console.ReadKey();
}
}
It seems that WebClient is also good to use. However, HttpClient has richer APIs. HttpClient encapsulates received information in the HttpResponseMessage class and sends the request information to HttpRequestMessage.
The console application references the following:
System. Net. Http. dll
System. Net. Http. Formatting. dll
Write as follows:
static void Main(string[] args)
{
Console. WriteLine ("obtain the content of ASP. NET Web API service as follows :");
HttpClient proxy = new HttpClient();
proxy.GetAsync("http://localhost:2497/api/Person").ContinueWith((previous) =>
{
HttpResponseMessage response = previous.Result;
response.Content.ReadAsStringAsync().ContinueWith((a) =>
{
foreach (var item in a.Result)
{
Console.WriteLine(item.ToString());
}
});
});
Console.ReadKey(true);
}
The above is a simple example of creating a simple ASP. NET Web API service and consuming services using WebClient and HttpClient.