在項目開發的過程中,WebService是經常要用的,當調用WebService方法時,需要經過服務的驗證才可以調用,一般就是用戶名/密碼驗證,還有一個就是證書.下面程序使用的是用戶名/密碼的方式,很簡單的一個程序.
項目截圖:
先看服務端的代碼(ws_Service)
MySoapHeader.cs 這里通過繼承SoapHeader實現對用戶名/密碼的驗證
public class MySoapHeader:System.Web.Services.Protocols.SoapHeader
{
private string userID = string.Empty;
private string userPW = string.Empty;
public string UserId
{
get { return userID; }
set { userID = value; }
}
public string UserPW
{
get { return userPW; }
set { userPW = value; }
}
public MySoapHeader()
{ }
public MySoapHeader(string name, string password)
{
userID = name;
userPW = password;
}
private bool IsValid(string nUserId, string nPassWord, out string nMsg)
{
nMsg = "";
try
{
if (nUserId == "admin" && nPassWord == "admin")
{
return true;
}
else
{
nMsg = "對不起,你無權調用Web服務";
return false;
}
}
catch
{
nMsg = "對不起,你無權調用Web服務";
return false;
}
}
public bool IsValid(out string nMsg)
{
return IsValid(userID,userPW,out nMsg);
}
}
Service1.asmx文件代碼:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class Service1 : System.Web.Services.WebService
{
public MySoapHeader myHeader = new MySoapHeader();
[WebMethod]
public string GetMsg()
{
Thread.Sleep(5000);
return "Hello World";
}
[SoapHeader("myHeader")]
[WebMethod(Description="獲取用戶列表")]
public string GetMain()
{
string msg = "";
if (!myHeader.IsValid(out msg))
{
return msg;
}
return "Main";
}
}
這里面有兩個方法,其中GetMsg方法是不需要驗證的,而GetMain方法需要進行用戶名/密碼的驗證,這個可以在客戶端調用時進行驗證.
客戶端添加對服務端的引用…
Program.cs文件
class Program
{
static void Main(string[] args)
{
localhost.Service1SoapClient proxy = new ws_Client.localhost.Service1SoapClient();
MySoapHeader header = new MySoapHeader();
header.UserId = "admin";
header.UserPW = "admin";
string result = proxy.GetMain(header);
//string result = proxy.GetMsg();
Console.WriteLine(result);
Console.ReadKey();
}
}

