在webservice裏添加以下類web
public class MySoapHeader : SoapHeader { private string strUserName = string.Empty; private string strPassWord = string.Empty; public MySoapHeader() { } public MySoapHeader(string username, string password) { this.strUserName = username; this.strPassWord = password; } #region 構造 /// <summary> /// 用戶名 /// </summary> public string UserName { get { return strUserName; } set { strUserName = value; } } /// <summary> /// 密碼 /// </summary> public string PassWord { get { return strPassWord; } set { strPassWord = value; } } #endregion #region 檢測是否正確登陸 /// <summary> /// 檢測是否正確登陸 /// </summary> /// <returns></returns> public bool ValideUser(out string msg ) { msg = ""; if (strUserName == "admin" && strPassWord == "123456") //在這裏設置身份驗證的帳號和密碼 { return true; } else { msg = "您無權調用次服務,請聯繫管理員!"; return false; } } #endregion }
在添加方法的時候添加以下代碼windows
public MySoapHeader header = new MySoapHeader (); ////定義用戶身份驗證類變量header [System.Web.Services.Protocols.SoapHeader("header")] [WebMethod] public string GetUserName(string userID) { string msg = ""; if (!header.ValideUser(out msg)) //驗證 { return msg; }
var data = new DALwbstest.UuserOP().GetUser(userID); if (data != null) { return data.UsernameCN; } else { return "沒有此人"; } }
調用的時候就須要帳號密碼驗證,代碼以下ide
WebReference.Npomwbs webClient = new Npomwbs(); MySoapHeader head = new MySoapHeader (); head.UserName = "admin"; //在webservice裏設置的帳號和密碼 head.PassWord = "123456"; webClient.MySoapHeaderValue = head; string name = webClient.GetUserName(txtID.Text); //調用須要驗證的方法
在webservice發佈iis的時候設置以下,添加訪問該webservice須要的帳戶和密碼 this
身份驗證設置成windows身份驗證spa
調用的時候就須要帳號密碼驗證,不然會提示沒有受權, 添加以下代碼3d
WebReference.Npomwbs webClient = new Npomwbs(); webClient.Credentials = new System.Net.NetworkCredential("admin","123456"); //這裏就是你剛填寫的帳號和密碼 string name = webClient.GetUserName(txtID.Text); // 調用方法
在項目上右鍵添加服務引用code
在高級裏添加web引用,在彈出的框裏輸入你發佈的webservice地址,點右側箭頭,點擊添加引用,添加引用成功blog
添加引用成功後就能夠調用了開發