ASP. NET Web API Tutorial 3.3 calling the Web API through a WPF application (C #)

Source: Internet
Author: User
Tags http post

Reference page:

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-static-files.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/setup-mvc.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/mvc-design-pattern.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/mvc-routing.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/attribute-route.html

Note: This article is part of the ASP. NET Web API Series tutorial, if you are looking at this blog post for the first time, please look at the previous content first.

3.3 Calling a Web API from a WPF application (C #)
3.3 Calling the Web API through a WPF application (C #)

This article quoted: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-wpf-application

by Mike Wasson | August 22, 2012
Mike Wasson | Date: 2012-8-22

This tutorial shows what to call a Web API from a Windows Presentation Foundation (WPF) application, using httpclient .
This tutorial shows how to invoke the Web API with HttpClient through a WPF application (the Windows Presentation foundation-windows Performance Foundation, a WPF application refers to a regular window application-translator note).

The main purpose of this tutorial was to see how asynchronous operations was handled in HttpClient. In this tutorial, we'll consume the "Productstore" API, described in "Creating a Web API that Supports CRUD Operations".
The main purpose of this tutorial is to examine how asynchronous operations are handled in HttpClient . In this tutorial, we will use the "Productstore" API described in the section "Creating Web APIs that support crud operations."

Before you read the tutorial, you might want to the read calling a Web API from a. NET Client. That's article introduces some of the concepts that I use in this tutorial.
Before reading this article, you may want to read "pass." NET client calls the Web API (the previous section of this series of tutorials-the translator's note). Some of the concepts used in this tutorial are described in this article.

Asynchronous Calls
asynchronous invocation

HttpClient is designed to be non-blocking. Potentially long-running operations is implemented as asynchonrous methods, such as Getasync and postasync . These methods return without waiting for the operation to complete. The previous tutorial (calling a Web API from a Console application) showed only blocking calls:
HttpClient is designed to be non-blocking. Potentially, long-running operations are implemented as asynchronous methods, such asGetasync and postasync. These methods do not wait for the operation to complete before they are returned. The previous tutorial (calling the Web API from a console application) showed only blocking calls:

Httpresponsemessage response = client. Getasync ("Api/products"). Result;  Blocking call (blocked)!

This code blocks the calling thread is taking the Result property. That's OK for a console application and you should don't do it from a UI thread, because it blocks the UI from responding T o user input.
This code blocks the calling thread by taking the Result property. This is fine for a console application, but you should not take this practice in a UI thread because it prevents the UI from responding to user input.

The asynchronous methods of HttpClient return Task objects that represent the asynchronous operation.
The HttpClient Async method returns a Task object that represents an asynchronous operation.

Create the WPF Project
To create a WPF project

Start Visual Studio. From the Start menu, select New Project. In the Templates pane, select installed Templates and expand the Visual C # node. In the list of project templates, select WPF application. Name the project and click OK.
Start Visual Studio. From the Start menu, select New Project. In the Templates panel, select installed templates, and expand the Viusal C # node. In the list of project templates, select WPF Application. Name this item and click "OK".

Open MainWindow.xaml and add the following XAML markup inside the Grid control:
Open MainWindow.xaml, and add the following XAML markup in the Grid control:

<stackpanel width= ">     <button name=" btngetproducts "click=" getproducts ">get Products</button >     <listbox name= "productslist" >         <ListBox.ItemTemplate>             <DataTemplate>                 < StackPanel margin= "2" >                     <textblock text= "{Binding path=name}"/>                     <textblock >price: $<run text= "{Binding path=price}"/>                          (<run text= "{Binding path=category}"/>) </TextBlock>                 </ stackpanel>             </DataTemplate>         </ListBox.ItemTemplate>     </ListBox> </ Stackpanel>

This markup defines a ListBox , that'll be data-bound to the list of products. The DataTemplate defines how each product would be displayed.
This tag defines a listbox(list box) that binds data to the product list. The DataTemplate(data template) defines how each product is displayed. (as shown in effect 3-4).

Figure 3-4. WPF interface Effects

Add the Model Class
To add a 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 is class defines a data object that HttpClient would write into the HTTP request body and read from the HTTP res Ponse body.
This class defines a data object thatHttpClient writes to the HTTP request body and reads it from the HTTP response body.

We ' ll also add an observable class for data binding:
We also want to add a visible object class (observable class) for data binding:

Class Productscollection:observablecollection<product> {public     void CopyFrom (ienumerable<product> Products)     {this         . Items.clear ();         foreach (var p in products)         {this             . Items.Add (P);         
This. OnCollectionChanged ( new NotifyCollectionChangedEventArgs (Notifycollectionchangedaction.reset));} }
Install NuGet Package Manager
Installing the NuGet Package Manager

NuGet Package Manager is the easiest-to-add Web API Client Library to a project. If you don't have a NuGet package Manager already installed, install it as follows.
The easiest way to add the Web API client library to your project is to install the NuGet Package Manager (NuGet packages manager). If you have not installed the NuGet Package Manager, follow the steps below to install it.

    1. Start Visual Studio.
      Start Visual Studio.
    2. From the Tools menu, select Extensions and Updates.
      Select extensions and updates from the Tools menu
    3. In the Extensions and Updates dialog, select Online.
      In the Extensions and Updates dialog box, select Online
    4. If you don't see "NuGet Package Manager", type "NuGet Package Manager" in the search box.
      If you don't see NuGet Package Manager, in the search box, enter NuGet packages manager.
    5. Select the NuGet package Manager and click Download.
      Select "NuGet Package Manager" and click "Download".
    6. After the download completes, you'll be prompted to install.
      After the download is complete, you will be prompted to install.
    7. After the installation completes, you might is prompted to restart Visual Studio.
      After the installation is complete, you may be prompted to restart Visual Studio.

The above installation procedure is shown in 3-5.

Figure 3-5. Installing the NuGet Package Manager

Install the Web API Client Libraries
Install the Web API client library

After NuGet package Manager was installed, add the Web API Client Libraries package to your project.
After installing the NuGet Package Manager, add the Web API client library package to your project. The steps are as follows:

    1. From the Tools menu, select Library package Manager. Note:if do don't see the This menu item, make sure the 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 NuGet Package Manager is installed correctly.
    2. Select Manage NuGet Packages for Solution ...
      Select "Manage NuGet packages for solution ..."
    3. In the Manage NuGet Packages Dialog, select Online.
      In the Manage NuGet Packages dialog box, select Online.
    4. In the Search box, type "Microsoft.AspNet.WebApi.Client".
      Enter "Microsoft.AspNet.WebApi.Client" in the search box.
    5. Select the ASP. NET Web API self Host package and click Install.
      Select the "ASP. NET Web API self-hosted package" and click "Install".
    6. After the package installs, click Close to close the dialog.
      Once this package is installed, click "Close" to close this dialog box.

The above installation is shown in step 3-6.

Figure 3-6. Install the Web API client library

Initialize HttpClient
Initialize HttpClient

From Solution Explorer, open the file MainWindow.xaml.cs. ADD the following code.
In Solution Explorer, open the MainWindow.xaml.cs file. Add the following code:

 namespace Wpfproductclient {using System;     Using System.Collections.Generic;     Using System.Net.Http;     Using System.Net.Http.Headers; Using System.Windows;         
public partial class Mainwindow:window {HttpClient client = new HttpClient (); Productscollection _products = new Productscollection ();
Public MainWindow () {InitializeComponent ();
Client. baseaddress = new Uri ("http://localhost:9000"); Client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json"));
this. Productslist.itemssource = _products; } } }

This code creates a new instance of HttpClient. It also sets the base URI to "Http://localhost:9000/", and sets the Accept header to "Application/json", which tells the S Erver to send data in JSON format.
This piece of code creates a new HttpClient instance. The base URI is also set to "Http://localhost:9000/", and the Accept header is set to "Application/json", which tells the server to send data in JSON format.

Notice that we also created a new Productscollection class and set it as the binding for the ListBox.
Note that we also created a new Productscollection class and set it to bind to the ListBox .

Getting a Resource (HTTP GET)
Get Resources (HTTP get)

If you is targeting. NET Framework 4.5, the async and await keywords make it much easier to write async Hronous code.
If your goal is. NET Framework 4.5 (meaning that the application you are developing will run on the. NET 4.5 platform-translator note), theasync and await keywords will make it easy for you to write asynchronous code.

If you is targeting. NET Framework 4.0 with Visual Studio, you can install the Async targeting Pack to get Async/awa IT support.
If your goal is to use the. NET Framework 4.0 of Visual Studio 2012, you can install the async targeting pack to get async/await support.

The following code queries the API for a list of products. ADD This code to the MainWindow class:
The following code queries the product List API. Add this code to the MainWindow class:

 private async void GetProducts (object sender, RoutedEventArgs e) {try {btngetproducts.isenabled = f Alse; 
var response = await client. Getasync ("api/products"); Response. Ensuresuccessstatuscode (); Throw On Error code (with error code times out of exception).
var products = await response. Content.readasasync<ienumerable<product>> (); _products. CopyFrom (products);
} catch (Newtonsoft.Json.JsonException jEx) {//This exception indicates a problem deserializing The request body. This exception indicates a problem in which the request body is being deserialized. MessageBox.Show (Jex.message); } catch (Httprequestexception ex) {MessageBox.Show (ex. Message); } finally {btngetproducts.isenabled = true; } }

The Getasync method sends an HTTP GET request. If The HTTP response indicates success, the response body contains a list of products in JSON format. To parse the list, call Readasasync. This method reads the response body and tries to deserialize it to a specified CLR type.
The Getasync method sends an HTTP GET request. If the HTTP response indicates success, the response experience contains a list of products in JSON format. To parse this list, call Readasasync. This method reads the response body and attempts to serialize it to a specific CLR type.

As their names imply, Getasync and Readasasync are asynchronous methods, meaning they return immediately , without waiting for the operation to complete. The await keyword suspends execution until the operation completes. For example:
As its name implies,getasync and Readasasync are asynchronous methods, meaning that they return immediately without waiting for the operation to complete. The await keyword suspends execution until the operation is complete. For example:

await the client. Getasync ("api/products");

The code that appears after this statement does isn't execute until the HTTP request is completed. But that does isn't mean the event handler blocks, waiting for getasync to complete. Just the Opposite-control returns to the caller. When the HTTP request is completed, execution continues from the point where it was suspended.
The code that appears after this statement is not executed until the HTTP request is complete. However, this does not mean that the event handler (event handler, also known as the incident handler -translator note) will block to wait for Getasync to complete. On the contrary-control is returned to the caller. When the HTTP request is complete, execution resumes from the point where it was hung.

If a method uses await, it must has the async modifier:
If a method uses await, it must have an async modifier:

async void GetProducts (object sender, RoutedEventArgs e)

Without the await keyword, you would need-to-call ContinueWith on the Task object:
Without this await keyword, you need to invoke the ContinueWithon the Task object:

private void GetProducts (object sender, RoutedEventArgs e) {btngetproducts.isenabled = false;
Client. Getasync ("Api/products/2"). ContinueWith ((t) + = {if (t.isfaulted) {MessageBox.Show (t.exception.message); Btngetproducts.isenabled = true; } else {var response = T.result; if (response. Issuccessstatuscode) {Response. Content.readasasync<ienumerable<product>> (). ContinueWith (t2 = {if (t2. isfaulted) {MessageBox.Show (t2. Exception.Message); Btngetproducts.isenabled = true; } else {var products = t2. Result; _products. CopyFrom (products); Btngetproducts.isenabled = true; } }, Taskscheduler.fromcurrentsynchronizationcontext ()); }}}, Taskscheduler.fromcurrentsynchronizationcontext ()); }

This type of code was difficult to get right, so it's recommended to target. NET 4.5, or if that's not possible, install th E Async targeting Pack.
This type of code is difficult to correct, so it is recommended that you target. NET 4.5, or, if this is not possible, install the Async targeting Pack (Async target package).

Creating a Resource (HTTP POST)
Create resource (HTTP POST)

Go back to the MainWindow.xaml file and add some (very) UI for creating a new product:
Go back to the MainWindow.xaml file and add some UI to create a new product:

<label fontweight= "Extrabold" >new product</label> <Label>Name</Label> <textbox name= " Textname "></TextBox> <Label>Price</Label> <textbox name=" Textprice "></TextBox> <Label>Category</Label> <textbox name= "textcategory" ></TextBox> <button name= " Btnpostproduct "click=" postproduct ">post product</button>

Now add the following code to the MainWindow class.
Now add the following code to the MainWindow class:

 private async void Postproduct (object sender, RoutedEventArgs e) {btnpostproduct.isenabled = false; 
try {var product = new Product () {Name = Textname.text, Price = Deci Mal. Parse (textprice.text), Category = Textcategory.text}; var response = await client. Postasjsonasync ("Api/products", product); Response. Ensuresuccessstatuscode (); Throw On error code (thrown when there is an error code).
_products. ADD (product); } catch (Httprequestexception ex) {MessageBox.Show (ex. Message); } catch (System.FormatException) {MessageBox.Show ("Price must is a number"); } finally {btnpostproduct.isenabled = true; } }

This code sends a POST request, contains a Product instance in JSON format. Postasjsonasync is a extension method defined in System.Net.Http.HttpClientExtensions. Internally, this method uses the JSON Media-type formatter to serialize the Product to JSON and write it into the Request body. For XML format, use the Postasxmlasync method.
This code sends a POST request that contains a JSON-formatted Product instance. Postasjsonasync is an extension method defined in the System.Net.Http.HttpClientExtensions. Internally, this method serializes the Product into JSON using the JSON media type formatter and writes it to the request body. For XML format, use the Postasxmlasync method.

Read this article if you feel something rewarding, please give a recommendation

ASP. NET Web API Tutorial 3.3 calling the Web API through a WPF application (C #)

Related Article

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.