js呼叫webservice:通過通過SOAP Header身份驗證
阿新 • • 發佈:2019-01-07
通過通過SOAP Header身份驗證
。
1.我們實現一個用於身份驗證的類,檔名MySoapHeader.cs
MySoapHeader
類繼承自System.Web.Services.Protocols.SoapHeader。且定義了兩個成員變數,UserName和
PassWord,還定義了一個使用者認證的函式ValideUser。它提供了對UserName和PassWord檢查的功能
- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.Services;
- using System.Web.Services.Protocols;
- /// <summary>
- ///MySoapHeader 的摘要說明
- /// </summary>
- public class MySoapHeader:SoapHeader
- {
- public MySoapHeader()
- {
- //
- //TODO: 在此處新增建構函式邏輯
- //
- }
- public string UserName;
- public string PassWord;
- public bool ValideUser(string in_UserName, string in_PassWord)
- {
- if ((in_UserName == "zxq") && (in_PassWord == "123456"))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
2.下面我們建立WebService.asmx WebService.cs程式碼如下:
- using System;
- using System.Collections;
- using System.Web;
- using System.Web.Services;
- using System.Web.Services.Protocols;
- /// <summary>
- ///WebService 的摘要說明
- /// </summary>
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- public class WebService : System.Web.Services.WebService
- {
- public WebService()
- {
- //如果使用設計的元件 ,請取消註釋以下行
- //InitializeComponent();
- }
- public MySoapHeader header; ////定義使用者身份驗證類變數header
- [WebMethod(Description = "使用者驗證測試 ")]
- [System.Web.Services.Protocols.SoapHeader("header")]//使用者身份驗證的soap頭
- public string HelloWorld(string contents)
- {
- //驗證是否有權訪問
- if (header.ValideUser(header.UserName, header.PassWord))
- {
- return contents + "執行了";
- }
- else
- {
- return "您沒有許可權訪問";
- }
- }
- }
3.客戶端 建立個Default.aspx
Default.aspx .cs程式碼
- using System;
- using System.Configuration;
- using System.Data;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- com.cn1yw.WebService test = new com.cn1yw.WebService();//web引用(改成您自己的)
- com.cn1yw.MySoapHeader Header = new com.cn1yw.MySoapHeader();//web引用建立soap頭物件(改成您自己的)
- //設定soap頭變數
- Header.UserName = "zxq";
- Header.PassWord = "123456";
- test.MySoapHeaderValue = Header;
- //呼叫web 方法
- Response.Write(test.HelloWorld("我是強"));
- }
- }