方法一:SoapHeader
辅助类:MySoapHeader
//SoapHeader 添加引用
using System.Web.Services.Protocols; #region 配置登录标头 public class MySoapHeader:SoapHeader
{
private string _strUserName = string.Empty;
private string _strPassWord = string.Empty; #region 构造方法
public MySoapHeader() { } public MySoapHeader(string userName, string passWord)
{
_strUserName = userName;
_strPassWord = passWord;
}
#endregion #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 检测是否正常登录
public bool CheckLogin()
{
if (_strUserName == "hkl" && _strPassWord == "")
{
return true;
}
else return false;
}
#endregion } #endregion
WebService代码
public MySoapHeader myHeader = new MySoapHeader(); [System.Web.Services.Protocols.SoapHeader("myHeader")]
[WebMethod(Description = "判断用户是否开通", EnableSession = true)]
public string GetValue(string strInputValue)
{
if (myHeader.CheckLogin())
{
string strReturnValue = strInputValue + "@身份验证已通过";
return strReturnValue;
}
else return "身份无效,请重试!";
}
新建一个web网页并添加web引用,在pageload方法中添加如下代码
localhost1.MySoapHeader myHeader = new localhost1.MySoapHeader();
myHeader.UserName = "hkl";
myHeader.PassWord = ""; localhost1.Service1 myTest = new localhost1.Service1();
myTest.MySoapHeaderValue = myHeader;
Response.Write(myTest.GetValue("This's my test Application for SoapHeader."));
运行即可查看结果。
方法二:Session
WebService代码
[WebMethod(Description = "检测是否通过验证", EnableSession = true)]
public bool CheckLogin(string strUserName, string strPassWord)
{
if (strUserName.Equals("xxx") && strPassWord.Equals(""))
{
Session["LoginState"] = true;
}
else Session["LoginState"] = false; return (bool)Session["LoginState"];
} [WebMethod(Description = "测试连接", EnableSession = true)]
public string GetValue(string strInputValue)
{
if (Session["LoginState"] == null || Session["LoginState"].Equals(false))
{
return "无效身份,请重试!";
}
else
{
string strReturnValue = strInputValue + "@身份验证已通过";
return strReturnValue;
}
}
新建一个web网页并添加web引用,在pageload方法中添加如下代码
localhost2.Service2 myTest = new localhost2.Service2();
myTest.CookieContainer = new System.Net.CookieContainer();
if (myTest.CheckLogin("xxx", ""))
{
Response.Write(myTest.GetValue("This is my test application for session."));
}
运行即可查看结果。