WebService1.asmx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace TestWs { /// <summary> /// WebService1 的摘要说明 /// </summary> [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 { public MySoapHeader soapHeader; [WebMethod(Description = "SoapHeader验证")] [System.Web.Services.Protocols.SoapHeader("soapHeader")] public string HelloWorld() { //简单验证用户信息 //可以通过数据库或其他方式验证 if ("admin".Equals(soapHeader.UserName) & "admin123".Equals(soapHeader.PassWord)) { return "用户验证通过!"; } else { return "对不起,您没有访问权限!"; } } } }
添加SoapHeader验证:创建基础的WebService服务后,根据需要,有时服务会需要权限来保证安全,这里通过添加SoapHeader验证(即Soap的头信息验证)来实现。
MySoapHeader.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TestWs { public class MySoapHeader: System.Web.Services.Protocols.SoapHeader { private string userName; private string passWord; public MySoapHeader() { } public MySoapHeader(string userName, string passWord) { this.userName = userName; this.passWord = passWord; } public string UserName { set { userName = value; } get { return userName; } } public string PassWord { set { passWord = value; } get { return passWord; } } } }
发布到IIS
下面为客户端调用
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ServiceTest { class Program { static void Main(string[] args) { //创建WebService服务实例 ServiceReference1.WebService1SoapClient service = new ServiceReference1.WebService1SoapClient(); //创建自定义SoapHeader对象实例 ServiceReference1.MySoapHeader header = new ServiceReference1.MySoapHeader(); //未设置SoapHeader的服务调用 Console.WriteLine("未设置SoapHeader的服务调用:" + service.HelloWorld(header)); Console.WriteLine(); //将用户名与密码存入SoapHeader; header.UserName = "admin"; header.PassWord = "admin123"; ////设置SoapHeader的服务调用 Console.WriteLine("未设置SoapHeader的服务调用:" + service.HelloWorld(header)); Console.Read(); } } }