Web Service 身份验证 解决方案一:通过通过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;
}
}
}
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代码如下:
Code
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("我是强"));
}
}
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("我是强"));
}
}