1、创建WEB项目,添加WEB服务WebService1.asmx,代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Services; 6 7 namespace WebService 8 { 9 /// <summary> 10 /// WebService1 的摘要说明 11 /// </summary> 12 [WebService(Namespace = "http://tempuri.org/")] 13 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 14 [System.ComponentModel.ToolboxItem(false)] 15 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 16 // [System.Web.Script.Services.ScriptService] 17 public class WebService1 : System.Web.Services.WebService 18 { 19 20 //声明Soap头实例 21 public MySoapHeader myHeader = new MySoapHeader(); 22 23 [System.Web.Services.Protocols.SoapHeader("myHeader")] 24 [WebMethod] 25 public string HelloWorld() 26 { 27 if (isAuthorized) 28 { 29 return "Hello World"; 30 } 31 else 32 { 33 return "You do not have power to do this operation!"; 34 } 35 } 36 37 [System.Web.Services.Protocols.SoapHeader("myHeader")] 38 [WebMethod] 39 public string InputYouName(string name) 40 { 41 if (isAuthorized) 42 { 43 return "Hello " + name; 44 } 45 else 46 { 47 return "You do not have power to do this operation!"; 48 } 49 } 50 51 /// <summary> 52 /// 判断用户是否获得使用授权 53 /// </summary> 54 public bool isAuthorized 55 { 56 get 57 { 58 if (myHeader.UserName.Equals("pwd") & myHeader.PassWord.Equals("pwd")) 59 { 60 return true; 61 } 62 else 63 { 64 return false; 65 } 66 } 67 } 68 } 69 }
2、加入安全验证,在这个web项目中添加一个类文件MySoapHeader.cs,具体代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 5 namespace WebService 6 { 7 public class MySoapHeader : System.Web.Services.Protocols.SoapHeader 8 { 9 private string userName = string.Empty; 10 private string passWord = string.Empty; 11 12 /// <summary> 13 /// 构造函数 14 /// </summary> 15 public MySoapHeader() { } /// <summary> 16 /// 构造函数 17 /// </summary> 18 /// <param name="userName">用户名</param> 19 /// <param name="passWord">密码</param> 20 public MySoapHeader(string userName, string passWord) 21 { 22 this.userName = userName; 23 this.passWord = passWord; 24 } 25 26 /// <summary> 27 /// 获取或设置用户用户名 28 /// </summary> 29 public string UserName 30 { 31 get { return userName; } 32 set { userName = value; } 34 } 35 36 /// <summary> 37 /// 获取或设置用户密码 38 /// </summary> 39 public string PassWord 40 { 41 get { return passWord; } 42 set { passWord = value; } 43 } 44 } 45 }
3、客户端调用,新建一个项目,创建一个控制台程序,调用示例的详细代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WebServiceControlClient { class Program { static void Main(string[] args) { Service.WebService1SoapClient aa = new Service.WebService1SoapClient(); Service.MySoapHeader Header = new Service.MySoapHeader(); Header.PassWord = "pwd"; Header.UserName = "pwd"; Console.WriteLine(aa.HelloWorld(Header)+"\n"+aa.InputYouName(Header,"harry")); Console.Read(); } } }