在这篇文章中,WCF扮演服务器,向外提供LoginVaild服务;Silverlight扮演客户端,调用WCF提供的LoginVaild服务。思路有了,下面进行代码实现。
USE [test] GO /****** Object: Table [dbo].[T_User] Script Date: 09/28/2014 21:12:02 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[T_User]( [username] [varchar](20) NOT NULL, [password] [varchar](20) NOT NULL, CONSTRAINT [PK_T_User] PRIMARY KEY CLUSTERED ( [username] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO INSERT [dbo].[T_User] ([username], [password]) VALUES (N'admin', N'admin')
1.新建一个WCF服务库项目,在默认生成的IServer1.cs接口在添加LoginVaild服务的声明:
[OperationContract]
bool LoginVaild(string userName, string password); 2.添加ADO.Net实体数据模型文件--Model.edmx,用于对数据表T_User的访问;
3.在Service1.svc中对LoginVaild方法进行实现:
public bool LoginVaild(string userName, string password)
{
bool result = false;
//需要访问的ADO.Net数据实体模型
using (SLtestEntitiesSecond entities = new SLtestEntitiesSecond())
{
var user = entities.T_User.Where(c => c.username == userName && c.password == password).SingleOrDefault();
if (user == null)
{
result = false;
}
else
{
result = true;
}
}
return result;
} 4.在项目的根目录添加跨域访问文件clientaccesspolicy.xml,内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
5.设定WCF服务器使用特定端口进行访问,方法:选中WCF服务器项目-->邮件属性-->Web-->特定端口,输入1316。这样保证我们每次可以通过1316端口访问WCF提供的服务。
到此,WCF服务器端配置完成,选中Service1.svc文件,在浏览器中浏览器下WCF提供的服务。
private void button1_Click(object sender, RoutedEventArgs e)
{
string userName = txtusername.Text.Trim();
string password = txtpassword.Text.Trim();
Service1Client client = new Service1Client();
client.LoginVaildCompleted += new EventHandler<LoginVaildCompletedEventArgs>(client_LoginVaildCompleted);
client.LoginVaildAsync(userName, password);
client.CloseAsync();
}
void client_LoginVaildCompleted(object sender, LoginVaildCompletedEventArgs e)
{
if (e.Error == null)
{
//MessageBox.Show(e.Result.ToString());
if (e.Result == true)
{
this.Content = new MainPage();
}
else
{
MessageBox.Show("用户名或密码错误!");
}
}
else
{
MessageBox.Show(e.Error.ToString());
}
} 4.在App.xaml配置文件设置Login.xaml为起始页,代码如下: private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new Login();
} 到此,客户端配置完成,运行Silverlight客户端项目即可查看结果。源码下载地址:http://pan.baidu.com/s/1mgn3IEO原文:http://blog.csdn.net/quwenzhe/article/details/39646885