This experience uses HttpClient to consume the ASP. NET WEB API service, the example is relatively simple.
Tap file, new, project.
Select the ASP. NET Web API project.
Create the Person.cs class under 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 under the Controllers folder.
public class Personcontroller:apicontroller
{
}
Create a management-compliant method, 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"}
};
}
}
In the browser, enter:
Http://localhost:2497/api/Person
Http://localhost:2497/api/Person/AllPersons
Can get to the data.
Create a console application under the solution.
Under the console, refer to System.Net and write the following:
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".
If you want to get the XML format, you can set the headers property of the 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 ();
}
}
WebClient seems to be good to use, but HttpClient has a richer API. HttpClient encapsulates the received information in the Httpresponsemessage class, encapsulating the requested information into the httprequestmessage.
In the console application, refer to the following:
System.Net.Http.dll
System.Net.Http.Formatting.dll
Write the following:
static void Main (string[] args)
{
Console.WriteLine ("Get the ASP. NET WEB API Service content 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);
}
These are simple examples of creating a simple ASP. NET Web API service and using WebClient and httpclient consumer services.
Consuming the ASP. NET WEB API service using HttpClient