1.新建项目WebService1
2.创建APISoapHeader,继承
System.Web.Services.Protocols.SoapHeader
APISoapHeader代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebService1 { public class APISoapHeader:System.Web.Services.Protocols.SoapHeader { private string _localhostkey = string.Empty; private string _secretkey = string.Empty; ////// 构造函数 /// public APISoapHeader() { //配置文件的SoapHeader_APIKey this._localhostkey = System.Configuration.ConfigurationManager.AppSettings.Get("SoapHeader_APIKey"); } ////// 获取或设置密钥 /// public string SecretKey { get { return this._secretkey; } set { this._secretkey = value; } } ////// 是否为安全的API调用 /// public bool IsSafeCall { get { if (this._localhostkey == this._secretkey) return true; else return false; } } } }
WebService1项目的配置文件(web.config)
Service1.asmx 代码结构
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebService1 { ////// Service1 的摘要说明 /// [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 Service1 : System.Web.Services.WebService { public APISoapHeader soapHeader = new APISoapHeader();//声明header [System.Web.Services.Protocols.SoapHeader("soapHeader")]//表明调用时需要传入header [WebMethod] public string HelloWorld() { if (!soapHeader.IsSafeCall)//传入的自定义APISoapHeader不正确,讲返回“你好!” { return "你好!"; } return "Hello World"; } } }
客户端调用:引用服务应用,ServiceReference1
ServiceReference1.Service1SoapClient soap = new WebApplication1.ServiceReference1.Service1SoapClient(); protected void Page_Load(object sender, EventArgs e) { ServiceReference1.APISoapHeader SoapHeader = new WebApplication1.ServiceReference1.APISoapHeader(); //设置SoapHeader Key SoapHeader.SecretKey = "1127d575-5633-4b97-a0fd-bb6bfb0d27de 5"; //WebService的方法HelloWorld没有使用APISoapHeader作参数,但是声明了 [System.Web.Services.Protocols.SoapHeader("soapHeader")] Response.Write(soap.HelloWorld(SoapHeader)); }