Webservice Session使用方法 又一篇

在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 完成了

posted on 2011-04-01 10:56  Jan.David  阅读(4331)  评论(2)    收藏  举报

导航