【ASP.NET Web API教程】3.3 通过WPF应用程序调用Web API(C#),

参考页面:

注:本文是【ASP.NET Web
API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。

注:本文是【ASP.NET Web
API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。

3.3 Calling a Web API From a WPF Application (C#) 3.3 通过WPF应用程序调用Web API(C#)

本文引自:

By Mike Wasson | August 22, 2012
作者:Mike Wasson | 日期:2012-8-22

This tutorial shows how to call a web API from a Windows Presentation
Foundation (WPF) application, using HttpClient.
本教程展示如何用HttpClient通过WPF应用程序(Windows Presentation
Foundation — Windows表现基础,WPF应用程序指常规的窗口应用程序 —
译者注)调用Web API。

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”.
本教程的主要目的是考查在HttpClient中如何处理异步操作。在本教程中,我们将使用在“创建支持CRUD操作的Web
API”小节中描述的“ProductStore”API。

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.
在阅读这篇文章之前,你或许想阅读“通过.NET客户端调用Web
API”(本系列教程的上一小节 —
译者注)。这篇文章中介绍了本教程使用的一些概念。

3.3 Calling a Web API From a WPF Application (C#) 3.3 通过WPF应用程序调用Web API(C#)

本文引自:

By Mike Wasson | August 22, 2012
作者:Mike Wasson | 日期:2012-8-22

This tutorial shows how to call a web API from a Windows Presentation
Foundation (WPF) application, using HttpClient.
本教程展示如何用HttpClient通过WPF应用程序(Windows Presentation
Foundation — Windows表现基础,WPF应用程序指常规的窗口应用程序 —
译者注)调用Web API。

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”.
本教程的主要目的是考查在HttpClient中如何处理异步操作。在本教程中,我们将使用在“创建支持CRUD操作的Web
API”小节中描述的“ProductStore”API。

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.
在阅读这篇文章之前,你或许想阅读“通过.NET客户端调用Web
API”(本系列教程的上一小节
— 译者注)。这篇文章中介绍了本教程使用的一些概念。

Asynchronous Calls 异步调用

HttpClient is designed to be non-blocking. Potentially long-running
operations are 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被设计成是非阻塞的。潜在地,长时间运行的操作是作为异步方法实现的,例如,GetAsyncPostAsync。这些方法不会等待操作完成便会返回。上一教程(通过控制台应用程序调用Web
API)只展示了阻塞调用:

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

This code blocks the calling thread by taking the Result property.
That’s OK for a console application, but you should not do it from a UI
thread, because it blocks the UI from responding to user input.
这段代码通过采用Result属性,会阻塞调用线程。对于一个控制台应用程序,这没问题,但你不应该在一个UI线程中采用这一做法,因为这会阻止UI去响应用户输入。

The asynchronous methods of HttpClient return Task objects that
represent the asynchronous operation.
HttpClient的异步方法会返回表示异步操作的Task对象。

Asynchronous Calls 异步调用

HttpClient is designed to be non-blocking. Potentially long-running
operations are 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被设计成是非阻塞的。潜在地,长时间运行的操作是作为异步方法实现的,例如,GetAsyncPostAsync。这些方法不会等待操作完成便会返回。上一教程(通过控制台应用程序调用Web
API)只展示了阻塞调用:

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

This code blocks the calling thread by taking the Result property.
That’s OK for a console application, but you should not do it from a UI
thread, because it blocks the UI from responding to user input.
这段代码通过采用Result属性,会阻塞调用线程。对于一个控制台应用程序,这没问题,但你不应该在一个UI线程中采用这一做法,因为这会阻止UI去响应用户输入。

The asynchronous methods of HttpClient return Task objects that
represent the asynchronous operation.
HttpClient的异步方法会返回表示异步操作的Task对象。

Create the WPF Project 创建WPF项目

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.
启动Visual
Studio。从“开始”菜单选择“新项目”。在“模板”面板中,选择“已安装模板”,并展开“Viusal
C#”节点。在项目模板列表中,选择“WPF应用程序”。命名此项目并点击“OK”。

Open MainWindow.xaml and add the following XAML markup inside the
Grid control:
打开MainWindow.xaml,并在Grid控件中添加以下XAML标记:

<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 defines a ListBox that will be data-bound to the list of
products. The DataTemplate defines how each product will be
displayed.
这段标记定义了一个将被数据绑定到产品列表的ListBox(列表框)。DataTemplate(数据模板)定义了如何显示每个产品。(其效果如图3-4所示)。

美高梅电子游戏 1

图3-4. WPF界面效果

Create the WPF Project 创建WPF项目

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.
启动Visual
Studio。从“开始”菜单选择“新项目”。在“模板”面板中,选择“已安装模板”,并展开“Viusal
C#”节点。在项目模板列表中,选择“WPF应用程序”。命名此项目并点击“OK”。

Open MainWindow.xaml and add the following XAML markup inside the
Grid control:
打开MainWindow.xaml,并在Grid控件中添加以下XAML标记:

<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 defines a ListBox that will be data-bound to the list of
products. The DataTemplate defines how each product will be
displayed.
这段标记定义了一个将被数据绑定到产品列表的ListBox(列表框)。DataTemplate(数据模板)定义了如何显示每个产品。(其效果如图3-4所示)。

美高梅电子游戏 2

图3-4. WPF界面效果

Add the Model Class 添加模型类

Add the following class 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 that HttpClient will write into the
HTTP request body and read from the HTTP response body.
这个类定义了一个数据对象,HttpClient将把它写入HTTP请求体,也从HTTP响应体中读取它。

We’ll also add an observable class for data binding:
我们也要添加一个用于数据绑定的可见对象类(observable class):

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)); 
    } 
}

Add the Model Class 添加模型类

Add the following class 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 that HttpClient will write into the
HTTP request body and read from the HTTP response body.
这个类定义了一个数据对象,HttpClient将把它写入HTTP请求体,也从HTTP响应体中读取它。

We’ll also add an observable class for data binding:
我们也要添加一个用于数据绑定的可见对象类(observable class):

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)); 
    } 
}

Author

发表评论

电子邮件地址不会被公开。 必填项已用*标注