【ASP.NET Web API教程】3.3 通过WPF应用程序调用Web API(C#)
注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。
3.3 Calling a Web API From a WPF Application (C#)
3.3 通过WPF应用程序调用Web API(C#)
本文引自: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 | 日期: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被设计成是非阻塞的。潜在地,长时间运行的操作是作为异步方法实现的,例如,GetAsync和PostAsync。这些方法不会等待操作完成便会返回。上一教程(通过控制台应用程序调用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 Tem