自定义类继承SoapHeader用户在webservice表头传递凭据
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services.Protocols;namespace FormsAuth.WebService{ public class SoapHeaderCredential:SoapHeader { private string strUserName = string.Empty; private string strPassWord = string.Empty; public SoapHeaderCredential() { } public SoapHeaderCredential(string username, string password) { this.strUserName = username; this.strPassWord = password; } #region 构造 用户名|密码 ////// 用户名 /// public string UserName { get { return strUserName; } set { strUserName = value; } } ////// 密码 /// public string PassWord { get { return strPassWord; } set { strPassWord = value; } } #endregion }}
添加接口IWebService
public interface IWebService{ SoapHeaderCredential HeaderCredential { get; set; }}
添加webservice实现IWebService接口
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using System.IO;using System.Xml.Serialization;using System.Text;using System.Web.Services.Protocols;namespace FormsAuth.WebService{ ////// WebService1 的摘要说明 /// [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService, IWebService { [WebMethod] [SoapHeader("HeaderCredential")] public string HelloWorld() { SpSoapHeader.CheckLogin(this); return "hello word"; } #region IWebService 成员 public SoapHeaderCredential HeaderCredential { get; set; } #endregion }}
SpSoapHeader用户验证
public class SpSoapHeader { ////// 检测是否正确登录 /// ///public static bool CheckLogin(IWebService service) { if (!(service.HeaderCredential.UserName == "user" && service.HeaderCredential.PassWord == "pass")) { throw new SoapException("Audit Fail", SoapException.ClientFaultCode, "Security"); } return true; } }
在客户端引用webservice,实例化webservice时制定凭据
WebReferences1.WebService1 client = new FormClient.WebReferences1.WebService1();WebReferences1.SoapHeaderCredential header = new FormClient.WebReferences1.SoapHeaderCredential();header.UserName = "user";header.PassWord = "pass";client.SoapHeaderCredentialValue = header;string ss = client.HelloWorld();