public class UserManager:SoapHeader
{
public string Name { get; set; }
public string Pwd { get; set; }
private bool CheckUser(string n,string p)
{
if(Name == "aaa" && Pwd == "bbb")
{
return true;
}
else
{
return false;
}
}
public bool CheckUser()
{
return CheckUser(Name, Pwd);
}
}
在服务端的WSDemo.asmx文件中输入以下代码
public class WSDemo : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
//标准一下CheckUser()方法使用哪个SoapHeader进行校验,客户端网站调用该方法时需要指定自己定义的SoapHeader内容
//这样,虽然CheckUser()并没有参数,但在在使用时,要先定义UserManager的SoapHeader的头,放在CheckUser中
public UserManager um;
[SoapHeader("um")]
[WebMethod(Description = "用户验证")]
public bool CheckUser()
{
if (um.CheckUser())
{
return true;
}
else
{
return false;
}
}
}
至此,服务端操作完毕
操作完服务端后,要在ServiceReference1上右击“更新服务引用”
图10 public partial class Index : System.Web.UI.Page
{
protected string stator = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
using (ServiceReference1.WSDemoSoapClient wsc = new WSDemoSoapClient())
{
//UserManager服务端中的类名
ServiceReference1.UserManager um = new UserManager();
um.Name = "aaa";
um.Pwd = "bbb";
stator = wsc.CheckUser(um)?"登录成功":"用户名或密码错误";//三目运算符,更据服务端返回值确定向浏览器输出内容
}
Response.Write(stator);
}
}
至此,客户端操作完毕,此时可发现在用户名和密码不对的情况下,浏览器所输入的值
public partial class Index : System.Web.UI.Page
{
protected string stator = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
using (ServiceReference1.WSDemoSoapClient client = new WSDemoSoapClient())
{
//要执行的方法
client.CheckUserCompleted += new EventHandler(client_CheckUserCompleted);
//为传参做准备,因为添加了“服务引用”所以在客户端也能点出服务端中公布的的方法来
ServiceReference1.UserManager um = new UserManager();
um.Name = "aaa";
um.Pwd = "bbb";
//开始执行
client.CheckUserAsync(um);
}
}
//要执行的方法
void client_CheckUserCompleted(object sender, CheckUserCompletedEventArgs e)
{
stator = e.Result ? "登录成功" : "登录失败";
Response.Write(stator);
}
}
public partial class Index : System.Web.UI.Page
{
protected string stator = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);//指明线程要执行方法
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);//获取从服务端中的返回值
bw.RunWorkerAsync();//开始执行
}
//获取从服务端中的返回值
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
stator = (bool)e.Result ? "登录成功" : "登录失败";
Response.Write(stator);
}
//指明线程要执行方法
void bw_DoWork(object sender, DoWorkEventArgs e)
{
//建立客户端和服务端的链接
using (ServiceReference1.WSDemoSoapClient client = new WSDemoSoapClient())
{
//对服务端公布方法UserManager进行实例化并赋值
UserManager um = new UserManager();
um.Name = "aaa";
um.Pwd = "bbb";
//调用服务端方法,并传入参数
e.Result = client.CheckUser(um);//注意e.Result = ...
}
}
}
至此,开线程异步客户端传参与服务器数据交互操作完毕