在webService 有两个方法
1.  [WebMethod(Description = "登录",EnableSession=true)]
public bool ClientLogin(string uNmae, string pwd)
{
//连接数据库验证用户登录

//创建一个session
System.Web.HttpContext.Current.Session["UserName"] = username;

return true;
}

2.[WebMethod(Description = "获取登录用户名称",EnableSession=true)]
public string GetUserName()
{
if (System.Web.HttpContext.Current.Session["UserName"] == null)
return null;
else
return
System.Web.HttpContext.Current.Session["UserName"].ToString();
}
注意EnableSession=true属性
在Client调用如下:
localhost.ServiceMethod methodName=new localhost.ServiceMethod();
methodName.GetUserName();//此处一直为空

解决方法
第一步:写一个类专门用来管理webService的实例化问题(此处主要是为了让类的实例共用一个CookieContainer ,只有这样session才能有值)
public class WebserviceClassInstance
{

static localhost.ServiceMethod  methodName;

public static localhost.ServiceMethod Service()
{
if (methodName== null)
{
methodName = new localhost.ServiceMethod();
methodName.CookieContainer = new System.Net.CookieContainer();
methodName.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
return methodName;
}
}
注意 methodName.CookieContainer = new System.Net.CookieContainer();
methodName.Credentials = System.Net.CredentialCache.DefaultCredentials;//不写可能会出现解决“HTTP Error 401 – Unauthorized” ,
也可以这样写methodName.Credentials = new NetworkCredential(userid,password,domainname),
第二步:   调用
WebserviceClassInstance.Service().ClientLogin(name,pwd);

WebserviceClassInstance.Service().GetUserName();//这里的session就不会为null了
Ok 完成了

相关文章:

  • 2021-12-16
  • 2021-09-07
  • 2021-12-30
  • 2022-12-23
  • 2021-09-15
  • 2021-06-18
  • 2021-11-21
猜你喜欢
  • 2022-12-23
  • 2021-05-29
  • 2022-12-23
  • 2021-12-16
  • 2021-08-07
  • 2021-12-06
相关资源
相似解决方案