转:
- 幸福小屋
1、自定义soapheader
namespace WebService2
{
/// <summary>
/// Service1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//[ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
public SecurityHeader currentUser;
public Service1()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod, SoapHeader("currentUser")]
public string GetResult(string queryString)
{
if (ValidateUser(currentUser.UserName, currentUser.UserPass))
{
return queryString;
}
else
{
return "您不能使用该服务";
}
}
//判断逻辑
public bool ValidateUser(string user, string pass)
{
if (user.Equals("user") && pass.Equals("user"))
return true;
else
return false;
}
}
//继承SoapHeader
public class SecurityHeader : System.Web.Services.Protocols.SoapHeader
{
public string UserName;
public string UserPass;
}
}
2、客户端调用web服务,现将webService引用到客户端程序
private void button1_Click(object sender, EventArgs e)
{
//先定义soapheader
Text_WebService.localhost.SecurityHeader header = new Text_WebService.localhost.SecurityHeader();
header.UserName =textBox1.Text;
header.UserPass =textBox2.Text;
Text_WebService.localhost.GetResultRequest service = new Text_WebService.localhost.GetResultRequest();
service.SecurityHeader =header;
Text_WebService.localhost.Service1SoapClient result = new Text_WebService.localhost.Service1SoapClient();
//result.GetResult(header, "123")
//调用服务器端的方法
MessageBox.Show(result.GetResult(header, "123"));
}