[ASP. NET Web API tutorial] 3.3 Use a WPF Application to call a Web API (C #),

Source: Internet
Author: User

[ASP. NET Web API tutorial] 3.3 Use a WPF Application to call a Web API (C #),

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 reading this blog for the first time, read the previous content first.

3.3 Calling a Web API From a WPF Application (C #)
3.3 Use a WPF Application to call Web APIs (C #)

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

By Mike Wasson | August 22,201 2
Author: Mike Wasson | Date:

This tutorial shows how to call a web API from a Windows Presentation Foundation (WPF) application, usingHttpClient.
This tutorial shows how to useHttpClientYou can call a Web API by using a Windows Presentation Foundation (Windows Presentation Foundation.

The main purpose of this tutorial is to see how asynchronous operations are handled in HttpClient. in this tutorial, we will consume the "ProductStore" API, described in "Creating a Web API that Supports CRUD Operations ".
The main purpose of this tutorial is to examineHttpClient. In this tutorial, we will use the "ProductStore" API described in "create a Web API that supports CRUD operations.

Before you read this tutorial, you might want to read Calling a Web API From a. NET Client. That article introduces some of the concepts that I use in this tutorial.
Before reading this article, you may want to read "call Web APIs through the. NET client" (the Translator's note in the previous section of this series of tutorials ). This article introduces some concepts used in this tutorial.

Asynchronous cballs
Asynchronous call

HttpClientIs designed to be non-blocking. Potentially long-running operations are implemented as asynchonrous methods, suchGetAsyncAndPostAsync. These methods return without waiting for the operation to complete. The previous tutorial (Calling a Web API From a Console Application) showed only blocking CILS:
HttpClientDesigned to be non-blocking. Potentially, long-running operations are implemented as Asynchronous methods, for example,GetAsyncAndPostAsync. These methods will not be returned after the operation is completed. The previous tutorial (calling Web APIs through the console application) only shows blocked calls:

HttpResponseMessage response = client. GetAsync ("api/products"). Result; // Blocking call (Blocking )!

This code blocks the calling thread by takingResultProperty. That's OK for a console application, but you shoshould not do it from a UI thread, because it blocks the UI from responding to user input.
This Code usesResultAttribute to block the calling thread. This is okay for a console application, but you should not use this method in a UI thread because it will prevent the UI from responding to user input.

The asynchronous methodsHttpClientReturnTaskObjects that represent the asynchronous operation.
HttpClientWill returnTaskObject.

Create the WPF Project
Create a WPF Project

Start Visual Studio. From the Start menu, selectNew Project. InTemplatesPane, selectInstalled TemplatesAnd expandVisual C #Node. In the list of project templates, selectWPF Application. Name the project and clickOK.
Start Visual Studio. Select "new project" from the "Start" menu ". On the "template" Panel, select "installed template" and expand the "Viusal C #" node. In the project template list, select "WPF application ". Name the project and click "OK ".

Open MainWindow. xaml and add the following XAML markup insideGridControl:
Open MainWindow. xaml andGridAdd the following XAML tag to the control:

<StackPanel Width="250" >     <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 definesListBoxThat will be data-bound to the list of products.DataTemplateDefines how each product will be displayed.
This tag defines a tag that binds data to the product list.ListBox(List box ).DataTemplate(Data Template) defines how to display each product. (The effect is shown in 3-4 ).

Figure 3-4. WPF interface effect

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 defines a data object thatHttpClientWill write into the HTTP request body and read from the HTTP response body.
This class defines a data object,HttpClientWrite it into the HTTP Request body and read it from the HTTP response body.

We'll also add an observable class for data binding:
We also need to add an 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
Install NuGet Package Manager

NuGet Package Manager is the easiest way to add the Web API Client library to a project. If you do not have NuGet Package Manager already installed, install it as follows.
The easiest way to add a Web API client library to a project is to install "NuGet Package Manager )". If you have not installed the NuGet Package Manager, follow these steps.

The installation process is as follows.

Figure 3-5. Install the NuGet Package Manager

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

After NuGet Package Manager is 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 procedure is as follows:

The preceding installation steps are 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 server to send data in JSON format.
This Code creates a new HttpClient instance. You can also set the base URI to "http: // localhost: 9000/" and set the Accept header 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 forListBox.
Note: We have also created a new ProductsCollection class and set itListBox.

Getting a Resource (http get)
Obtain resources (http get)

If you are targeting. NET Framework 4.5,AsyncAndAwaitKeywords make it much easier to write asynchronous code.
If your target is. NET Framework 4.5 (that is, your developed application will run on the. NET 4.5 Platform ),AsyncAndAwaitKeyword makes it easy for you to write asynchronous code.

If you are targeting. NET Framework 4.0 with Visual Studio 2012, you can install the Async Targeting Pack to get async/await support.
If you are using. NET Framework 2012 of Visual Studio 4.0, you can install Async Targeting Pack to obtain 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 = false;
Var response = await client. GetAsync ("api/products"); response. EnsureSuccessStatusCode (); // Throw on error code (an exception is reported when an error code is returned ).
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 with deserializing the request body. MessageBox. Show (jEx. Message);} catch (HttpRequestException ex) {MessageBox. Show (ex. Message);} finally {btnGetProducts. IsEnabled = true ;}}

TheGetAsyncMethod 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, callReadAsAsync. This method reads the response body and tries to deserialize it to a specified CLR type.
GetAsyncMethod to send an http get request. If the HTTP response is successful, the response contains a list of products in JSON format. To parse this list, callReadAsAsync. This method reads the response body and tries to serialize it into a specific CLR type.

As their names imply,GetAsyncAndReadAsAsyncAre asynchronous methods, meaning they return immediately, without waiting for the operation to complete.AwaitKeyword suspends execution until the operation completes. For example:
As its name implies,GetAsyncAndReadAsAsyncIt is an asynchronous method, that is, they return immediately without waiting for the Operation to complete.AwaitKeyword will be suspended until the operation is completed. For example:

var response = await client.GetAsync("api/products");

The code that appears after this statement does not execute until the HTTP request is completed. But that does not mean the event handler blocks, waitingGetAsyncTo complete. Just the opposite-control returns to the caller. When the HTTP request is completed, execution continues from the point where it was susponded.
The code that appears after this statement will not be executed until the HTTP request is complete. But this does not mean that the event handler can also be calledEvent Handler-Translator's note) will be blocked to waitGetAsyncComplete. On the contrary-the control will return to the caller. When the HTTP request is complete, the execution continues from the starting point.

If a method usesAwait, It must haveAsyncModifier:
If a method is usedAwait, It must haveAsyncModifier:

private async void GetProducts(object sender, RoutedEventArgs e)

WithoutAwaitKeyword, you wowould need to callContinueWithOnTaskObject:
No suchAwaitKeyword, you need to callTaskObjectContinueWith:

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 is difficult to get right, so it's recommended to target. NET 4.5, or if that's not possible, install the Async Targeting Pack.
This type of code is difficult to correct, so we recommend that you set the target to. NET 4.5, or, if this is not possible, install Async Targeting Pack (Async target package ).

Creating a Resource (http post)
Create a resource (http post)

Go back to the MainWindow. xaml file and add some (very) UI for creating a new product:
Return to the MainWindow. xaml file and add the UI for creating 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.
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 = decimal. parse (textPrice. text), Category = textCategory. text}; var response = await client. postAsJsonAsync ("api/products", product); response. ensureSuccessStatusCode (); // Throw on error code (thrown when an error code exists ).
_ Products. add (product);} catch (HttpRequestException ex) {MessageBox. show (ex. message);} catch (System. formatException) {MessageBox. show ("Price must be a number");} finally {btnPostProduct. isEnabled = true ;}}

This code sends a POST request that contains a Product instance in JSON format. postAsJsonAsync is an 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 Product instance in JSON format. PostAsJsonAsync is an extension method defined in System. Net. Http. HttpClientExtensions. Internally, this method uses the JSON media formatter to serialize the Product into JSON and write it into the Request body. The PostAsXmlAsync method is used for XML format.

After reading this article, I 'd like to give it a try.Recommendation

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.