WebService⽤户名密码验证
在项⽬开发的过程中,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;
调用webservice服务}
}
catch
{
nMsg = "对不起,你⽆权调⽤Web服务";
return false;
}
}
public bool IsValid(out string nMsg)
{
return IsValid(userID,userPW,out nMsg);
}
}
Service1.asmx⽂件代码:
[WebService(Namespace = "/")]
[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();
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论