为 WCF 服务类添加一个新方法,使用 [OperationContract] 特性来修饰。如下添加一个方法:
[OperationContract ]
public string GetName() {
return "John" ;
}
正如你看见的,这是一个简单的方法返回一个硬编码的名字。
打开解决方案管理器。右键“ Service1.svc ”文件,并选择“设为起始页”。
按 Ctrl + F5 运行应用程序(或使用菜单“调试” –> “开始执行不调试”)。
在浏览器打开 Service1 元数据。忽略页面内容,从浏览器复制 URL 。 URL 类似于:
http://localhost:1873/Service1.svc
这个端口号可能会不同,但没有关系。
回到 Visual Studio 的解决方案管理器。右键 Silverlight 项目(不是 Web 项目)并选择“添加 Service引用”。
在地址域中,指定从浏览器中复制的URL,点击“前往”。
在底部左边,修改命名空间为“ MySampleService ”。
将看见如下屏幕:
点击“确定”添加服务引用。
现在可以从 Silverlight 客户端调用 WCF 访问。
为了做测试,做下面几步:
1. 打开 Page1.xaml 文件并添加一个文本框用于显示从WCF方法返回的字符串
2. 从 UserControl 中添加“Loaded”事件。
Page1.xaml 中的完整代码如下:
< UserControl x : Class ="Silverlight_With_WCF.Page"
xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns : x ="http://schemas.microsoft.com/winfx/2006/xaml"
Width ="400" Height ="300"
Loaded ="UserControl_Loaded">
<Gridx : Name ="LayoutRoot" Background ="White">
<TextBlockx : Name ="textblock1" Width ="200" Height ="30"></ TextBlock >
</Grid>
</ UserControl >
现在在后置代码中( Page1.xaml.cs )中,按如下方式添加 WCF 服务调用:
private void UserControl_Loaded(object sender,RoutedEventArgs e) {
MySampleService.Service1Client client =
new MySampleService.Service1Client ();
client.GetNameCompleted +=
new EventHandler <Silverlight_With_WCF.MySampleService.
GetNameCompletedEventArgs >(client_GetNameCompleted);
client.GetNameAsync();
}
void client_GetNameCompleted(object sender,
MySampleService.GetNameCompletedEventArgs e){
textblock1.Text = (string )e.Result;
}
在解决方案管理器中打开 Web 项目并设置 Silverlight测试页为起始页。运行项目。可以看见从Silverlight客户端调用 WCF 服务,并将结果显示在浏览器。(在这个例子中,从调用 WCF 服务返回的结果是“ John”名字并将名字显示在屏幕上)。
Silverlight入门知识学习目录