注:本文由BeyondVincent(破船)原创首发
转载请注明出处:BeyondVincent(破船)@DevDiv.com
本这篇文章中,我将向大家介绍如何在C#编程语言中,使用web services开发Windows Store apps。
在Windows Store apps中,访问web service是通过异步进行的,并使用关键字await。在这里,我创建一个简单的XAML+C#程序,来访问一个天气service,该service我是在网上找到的。如下URL:
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx
在此,通过输入城市的名称,然后通过访问webservice,就会返回相应城市的天气情况。
下面请跟我一步一步来:
1、首先使用C#模板创建一个Blank app,命名为BV_WebServiceDemo

2、在解决方案中的引用上单击右键,选择添加服务引用
3、在地址栏输入web service URL,然后点击转到,将会去查找这个web service
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

查找成功后,提供名称空间,然后单击确定

4、将会自动为这个天气服务生成一个服务引用。

5、在MainPage.xaml.cs文件中添加名称空间
using BV_WebServiceDemo.WeatherWebService;
6、下面来设计一下XAML页面(显示天气的详情)
代码比较多,详情请下载后面的附件查阅
在这里,上一个效果图

7、通过基于task的异步模型,来调用service。
下面是代码:
private async void GoButton_Click(object sender, RoutedEventArgs e) { ring.IsActive = true; WeatherWebServiceSoapClient proxy = new WeatherWebServiceSoapClient(); //string[] result = await proxy.getSupportCityAsync(inputZipCode.Text); if (inputZipCode.Text.Length == 0) { inputZipCode.Text = \\"大理\\"; } string[] result = await proxy.getWeatherbyCityNameAsync(inputZipCode.Text); if (result.Length > 0) { ring.IsActive = false; StringBuilder resultString = new StringBuilder(100); foreach (string temp in result) { resultString.AppendFormat(\\"{0}\n\\", temp); } resultDetails.Text = resultString.ToString(); } }
8、按F5,调试运行,查看结果
输入城市名称,然后单击查询按钮

代码下载