WCF服务应用程序端:
建立WCF服务应用程序,并连接数据库。
【1】:新建WCF服务应用程序。
【2】:在IService1.cs中,添加代码:
//登陆函数
[OperationContract]
bool LoginVaild(string username,string pwd);
然后,在Service1.svc.cs文件中 ,在接口上
点击右键,实现接口。
此时,会自动生成一个函数:
public bool LoginVaild(string username, string pwd)
{
throw new NotImplementedException();
}
在这个函数中添加登陆代码。
WCF连接数据库:
【3】:新建数据库:
并添加一个用户,用户名和密码都为:admin,方便后面登陆测试。
【2】:为WCF项目添加ADO.NET数据库实体模型
OK.
【4】:编写登陆代码:
public bool LoginVaild(string username, string password)
{
bool result = false;
using (SLtestEntities entities = new SLtestEntities())//建立实体模型代理
{
var user = entities.UserInfo.Where(c => c.user_name == username && c.password == password).SingleOrDefault();
if (user==null)
{
result = false;
}
else
{
result = true;
}
}
return result;
}
【5】:固定端口
WCF项目,右键=》属性=》
【6】:生成一下解决方案,在浏览器中打开Service1.svc,从而开启服务。至此,WCF完成。
Siverlight端:
【1】新建项目,建立Siverlight应用程序。
【2】:添加服务引用。
【3】:新建 Siverlight用户控件,作为登陆界面,命名为Login.xaml。改启动页面为Login.xaml。
【4】:编写登陆代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
string username = textBox1.Text.Trim();
string pwd = passwordBox1.Password.Trim();
Service1Client client = new Service1Client();
client.LoginVaildCompleted += new EventHandler<LoginVaildCompletedEventArgs>(client_LoginVaildCompleted);
client.LoginVaildAsync(username,pwd);
client.CloseAsync();
}
void client_LoginVaildCompleted(object sender, LoginVaildCompletedEventArgs e)
{
if (e.Error==null)
{
if (e.Result==true)
{
this.Content = new MainPage();//页面转跳到MainPage
}
else
{
MessageBox.Show("用户名或者密码错误!");
}
}
else
{
MessageBox.Show(e.Result.ToString());
}
}
运行项目,会发现出错了,错误如下:
错误原因,当Siverlight想WCF发出跨域请求时候,会问WCF是否允许接受跨域请求,怎么样WCF允许跨域请求呢?WCF必须有跨域文件
跨域文件名字必须是: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>
解决办法:在WCF项目中添加此跨域文件,并重新生成解决方案。
至此,本节内容结束。