的CookieContainer和Web服务
-
25-09-2019 - |
题
我的WebService:
public class Service1:WebService {
private readonly MNConnection _conn;
private MNLpu _lpu;
public Service1() {
_conn = new MNConnection();
}
[WebMethod(EnableSession = true)]
public void Open(string login, string password) {
_conn.Open(login, password);
_lpu = (MNLpu)_conn.CreateLPU();
}
[WebMethod(EnableSession = true)]
public decimal Get() {
return _lpu.Count;
}
}
当我把它从外部的控制台应用程序,在最后一行它的显示我的NullReferenceException:
CookieContainer cookie = new CookieContainer();
Service1 lh = new Service1 {CookieContainer = cookie};
lh.Open("login", "pwd");
Console.WriteLine(lh.Get());
如果删除打开()从web服务和插入件构造这样的行它的方法正常工作:
_conn.Open(login, password);
_lpu = (MNLpu)_conn.CreateLPU();
如何解决呢? 附: MNConnection - 我自己的类,它与作品的OracleConnection
解决方案
您每次调用Web方法将调用服务器端的一个新的Web服务,所以不是很好的保持任何私有变量上的Web服务。
有关两个通话,lh.Open和lh.Get,在服务器端,创建的WebService的两个不同的实例,即使你有你的客户端代理的只有一个单一的实例。
如果你想解决这个问题,那么你应该只使用HttpContext.Current.Session和存储对象的你有用的情况下在这个喜欢......
您应该改变你的web服务,如下...
[WebMethod(EnableSession = true)]
public void Open(string login, string password) {
MNConnection _conn = new MNConnection();
_conn.Open(login, password);
HttpContext.Current.Session["MyConn"] = _conn;
HttpContext.Current.Session["LPU"] = _conn.CreateLPU();
}
[WebMethod(EnableSession = true)]
public decimal Get() {
MNLPU _lpu = HttpContext.Current.Session["LPU"] as MNLPU;
return _lpu.Count;
}
不隶属于 StackOverflow