Pass. NET client invoke Web API (C #) __.net

Source: Internet
Author: User
Tags http post
3.2 Calling a Web API from a. NET Client (C #)
3.2 Pass. NET client invoke Web API (C #)

This article quoted from: Http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

by Mike Wasson | July 18, 2012
Author: Mike Wasson | Date: 2012-7-18

This tutorial shows the how to call a Web API from console application, using HttpClient.
This tutorial shows how to use HttpClient to invoke the Web API in a console application.

In this tutorial, we'll consume the "Productstore" API, described in creating a Web API that Supports CRUD Operations.
In this tutorial, we will use the "Productstore" API described in the "Creating a Web API that supports CRUD Operations (Section 2.1-translator) of this series of tutorials." Create the Console application
To create a console application

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.
Start Visual Studio and select New project from the Start page. Or choose New from the File menu, and then select Project.

In the Templates pane, select Installed Templates and expand the Visual C # node. Under Visual C #, select Windows. In the list of project templates, Selectconsole application. Name the project and click OK.
In the Templates panel, select installed templates and expand the Visual C # node. Under Visual C #, select Windows. In the list of project templates, select Console application. Name this item and click OK (see Figure 3-1).

Figure 3-1. Create a console project Install NuGet Package Manager
Install NuGet Package Manager

NuGet Package Manager is the easiest way to add the Web API Client Library to a project. If you don't have NuGet Package Manager already installed, install it as follows.
The NuGet Package Manager (NuGet Package Manager) is one of the easiest ways to add a Web API client library to a project. If NuGet Package Manager is not already installed, install it as follows. Start Visual Studio.
Start Visual Studio. From the Tools menu, select Extensions and Updates.
Select "Extensions and Updates" From the Tools menu in the Extensions and Updates dialog, select Online.
In the Expand and Update dialog box, select Online If you don ' t "NuGet Package Manager", type "NuGet Package Manager" in the search box.
If you do not see the NuGet Package Manager, enter "NuGet Package Manager" in the search box. Select the NuGet Package Manager and click Download.
Select "NuGet Package Manager" and click "Download". After the download completes, you are prompted to install.
When the download is complete, you will be prompted to install it. After the installation completes, your might is prompted to restart Visual Studio.
After the installation is complete, you may be prompted to restart Visual Studio.

The above installation process is shown in Figure 3-2.

Figure 3-2. Install NuGet Package Manager Install the Web API Client libraries
Installing the Web API client library

After NuGet Package Manager are installed, add the Web API Client libraries Package to your project.
After you install the NuGet Package Manager, add the Web API client library package to your project. The steps are as follows: From the Tools menu, select Library Package Manager. Note:if Do you don't have this menu item, make sure that NuGet Package Manager installed correctly.
From the Tools menu, select Library Package Manager. Note: If you do not see this menu item, make sure that the NuGet Package Manager is installed correctly. Select Manage NuGet Packages for Solution ...
Select "Manage NuGet package for solution ..." In the Manage Nu G get Packages Dialog, select Online.
In the Manage NuGet Package dialog box, select Online. In the Search box, type "Microsoft.AspNet.WebApi.Client".
Enter "Microsoft.AspNet.WebApi.Client" in the search box. Select the asp.net Web API Self Host Package and click Install.
Select the "ASP.net Web API self-managed package" and click "Install". After the package installs click on the dialog.
After the package is installed, click "Close" to close this dialog box.

The above installation steps are shown in Figure 3-3.

Figure 3-3. Install the Web API client library ADD the Model Class
Add Model class

ADD the following class to the application:
Add the following classes to the application:

Class Product 
{public 
    string Name {get; set;} 
    Public double price {get; set;} 
    public string Category {get; set;} 
}

This class creates a data object that httpclient'll write into the HTTP request body and read from the HTTP response bod Y.
This class creates a data object that HttpClient will write to the HTTP request body and read from the HTTP response body. Initialize httpclient
Initialize HttpClient

Create a new instance of HttpClient and initialize it as follows:
Create a new HttpClient instance and initialize it as follows:

Namespace Productstoreclient 
{ 
    using System; 
    Using System.Collections.Generic; 
    Using System.Net.Http; 
    
Class program { static void Main (string[] args) { httpclient client = new HttpClient (); Client. baseaddress = new Uri ("Http://localhost:9000/"); Add an Accept header for JSON format. Adds a accept header client to the JSON format . DEFAULTREQUESTHEADERS.ACCEPT.ADD ( new Mediatypewithqualityheadervalue ("Application/json"));}}

This code sets the base URI to "Http://localhost:9000/", and sets the Accept header to "Application/json", which tells the Server to send data in JSON format.
This code sets the base URI to "Http://localhost:9000/" and sets the Accept header to "Application/json", which tells the server to send the data in JSON format. getting a Resource (HTTP get)
Getting resources (HTTP get)

The following code shows how to query the APIs for a list of products:
The following code shows how to query the API for a product list:

List all products.
List all Products
httpresponsemessage response = client. Getasync ("Api/products"). result;  Blocking call (blocking invocation)! 
if (response. Issuccessstatuscode) 
{ 
    //Parse the response body. blocking!
    Resolves the response body. Blocking.
    var products = response. Content.readasasync<ienumerable<product>> (). result; 
    foreach (var p in products) 
    { 
        Console.WriteLine ("{0}\t{1};\t{2}", P.name, P.price, p.category); 
    } 
Else 
{ 
    Console.WriteLine (' {0} ({1}) ', (int) response. StatusCode, Response. reasonphrase); 
}

The getasync method sends an HTTP GET request. As the name Implies, getasyc is asynchronous. It returns immediately, without waiting for a response from the server. The return value was A task object that represents the asynchronous operation. When the operation completes, The task.result property contains the HTTP response. The
Getasync method sends an HTTP GET request. As its name implies, Getasync is asynchronous. It returns immediately and does not wait for the server to respond. The return value is a Task object that represents an asynchronous operation. When the operation completes, the Task.result property contains the HTTP response.

It is important to understand that taking The result property blocks your thread application the until St completes (or times out). Blocking in a console application are OK, but you should never does this to the UI thread of Windows application, because I T blocks the UI from responding to user input. In the next part of this tutorial, we'll be there to write non-blocking calls.
It is important to understand that, until the request completes (or times out), the process using the result property is blocked by the application thread. Blocking the console application is fine, but you should never do this on a Windows application's UI because it blocks the UI from responding to user input. In the next section of this tutorial, we'll see how to write Non-blocking calls.

If The HTTP response indicates success, the response body contains a list of all products in JSON format. To parse the list, call Readasasync. This method reads the "response" and tries to deserialize it to a specified CLR type. This is also asynchronous and because the body can be arbitrarily large. Again, taking the resultproperty blocks the thread.
If the HTTP response indicates success, the response body contains a JSON-formatted list of products. To parse this list, you call Readasasync. The method reads the response body and attempts to deserialize it into a specific CLR (Common language Runtime) type. This method is also asynchronous, because the body may have any size. Again, the process of adopting the result property is blocked by the thread.

Example HTTP Session:
HTTP Session Example:

Get http://localhost:9000/api/products http/1.1 
Accept:application/json 
host:localhost:9000 

http/1.1 OK Server:ASP.NET Development server/11.0.0.0 Date:mon, Aug-22:14:59 GMT x-aspnet-vers ion:4.0.30319 cache-control:no-cache pragma:no-cache Expires:-1 Content-type:application/json ; Charset=utf-8 content-length:183
[{"id": 1, "name": "Tomato Soup", "Category": "Groceries", "Price": 1.39},{"id": 2, "name": "Yo-Yo", "Category": " Toys "," Price ": 3.75},{" Id ": 3," Name ":" Hammer "," Category ":" Hardware "," Price ": 16.99}]

Getting a product by ID is similar:
Getting the product by ID is similar:

get a Products by ID//ID FETCH product
response = client. Getasync ("API/PRODUCTS/1"). result; 
if (response. Issuccessstatuscode) 
{ 
    //Parse the response body. blocking!
    Analytic response Hugh. Blocking.
    var product = response. Content.readasasync<product> (). result; 
    Console.WriteLine ("{0}\t{1};\t{2}", product. Name, product. Price, product. Category); 
} 
else 
{ 
    Console.WriteLine (' {0} ({1}) ', (int) response. StatusCode, Response. reasonphrase); 
}
media-type formatters
Media Type Formatter

Readasasync is a extension method defined in the System.Net.Http.HttpContentExtensions class. With no parameters, it uses the ' default set of Media-type formatters to try to parse the ' response body. The default formatters support JSON, XML, and form-url-encoded data. (For more information about Media-type formatters, the Formats and Model Binding.)
Readasasync is an extension method that is defined in the System.Net.Http.HttpContentExtensions class. Without parameters, it uses the default settings of the media type formatter to attempt to parse the response body. The default formatter supports JSON, XML, and URL-encoded form data (form-url-encoded data). (For more information about media type formatters, see Formatting and Model binding (chapter 6th of this tutorial series-Translator's note))

can also explicitly specify the media-types formatters to use. This is useful if you have a custom Media-type formatter.
You can also explicitly specify the media type formatter that you are using. If you have a custom media type formatter, this is useful.

var formatters = new List<mediatypeformatter> () { 
    new Mycustomformatter (), 
    new Jsonmediatypeformatter () , 
    new Xmlmediatypeformatter () 

Resp. Content.readasasync<ienumerable<product>> (formatters);
Creating a Resource (HTTP POST)
Create a resource (HTTP POST)

The following code sends a POST request that contains a Product instance in JSON format:
The following code sends a POST request that contains a product instance in JSON format:

Create a new product
///Create a new product
var gizmo = new Product () {Name = "gizmo", Price = +, Category = "Widget"}; 

Response = client. Postasjsonasync ("Api/products", Gizmo). result; if (response. Issuccessstatuscode) { Gizmouri = response. headers.location; } else { Console.WriteLine (' {0} ({1}) ', (int) response. StatusCode, Response. reasonphrase); }

Postasjsonasync is a extension method defined in System.Net.Http.HttpClientExtensions. It is equivalent to the following:
Postasjsonasync is an extension method that is defined in System.Net.Http.HttpClientExtensions. The preceding code is equivalent to the following code:


Create the JSON formatter. Creates a JSON formatter.
Use the JSON formatter to create the content of the ' request body. Use the JSON formatter to create the content of the request body.
Send the request. Send the request. var resp = client. Postasync ("api/products", content). result;

For XML format with the Postasxmlasync method.
For XML formats, use the Postasxmlasync method.

Example HTTP Session:
HTTP Session Example:

 POST http://localhost:9000/api/products http/1.1 Accept:application/json Content-type:application/json; Charset=utf-8 host:localhost:9000 content-length:50 expect:100-continue 
{"Name": "Gizmo", "Price": 100.0, "Categor Y ":" Widget "}
http/1.1 201 Created Server:ASP.NET Development server/11.0.0.0 Date:mon, Aug-22:15:00 GMT x-aspnet-version:4.0.30319 LOCATION:HTTP://LOCALHOST:9000/API/PRODUCTS/7 Cache-control:no-cache Pragma:no-cache Ex Pires:-1 Content-type:application/json; Charset=utf-8 content-length:57 connection:close
{"Id": 7, "Name": "Gizmo", "Category": "Widget", "Price": 100.0}

By default, the JSON formatter sets the Content-type to "Application/json". You can also specify the media type explicitly. For example, suppose the "application/vnd.example.product" is your media type for product instances. Could set this media type as follows:
By default, the JSON formatter sets the Content-type (content type) to "Application/json". You can also specify the media type explicitly. For example, suppose "application/vnd.example.product" is the type of media you use for the product instance. You can set up this type of media as follows:

Httpcontent content = new Objectcontent<product> (Product, Jsonformatter,
    "application/vnd.example.product +json ");
Updating a Resource (HTTP put)
Update a resource (HTTP put)

The following code sends a PUT request.
The following code sends a PUT request:

Update a
products//update a product
Gizmo. Price = 99.9; 
Response = client. Putasjsonasync (Gizmouri.pathandquery, Gizmo). result; 
Console.WriteLine (' {0} ({1}) ', (int) response. StatusCode, Response. Reasonphrase);

The Putasjsonasync is postasjsonasync, except it sends a PUT request instead of POST.
The Putasjsonasync method is similar to the Postasjsonasync, except that it sends a put request, not a post. Deleting a Resource (HTTP DELETE)
Delete a resource (HTTP delete)

By now, you can probably predict and send a DELETE request:
Now, you may already be able to predict how to send a delete request:

Delete a 
products//delete a product
response = client. Deleteasync (Gizmouri). result; 
Console.WriteLine (' {0} ({1}) ', (int) response. StatusCode, Response. Reasonphrase);

Like get, a DELETE request does not have a request body, so don ' t need to specify JSON or XML format.
As with GET, delete requests do not have a request body, so you do not have to specify JSON or XML format. Error Handling
Error handling

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.