2010-09-27 52 views
0

我的WebService:的CookieContainer和Web服务

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服务中删除Open()方法和插入到构造这样的行它的工作正常:

 _conn.Open(login, password); 
     _lpu = (MNLpu)_conn.CreateLPU(); 

如何解决它? P.S. MNConnection - 我自己的类,它适用于OracleConnection。

回答

1

您对Web方法的每次调用都会在服务器端调用一个新的Web服务,因此在Web Service上保留任何私有变量并不好。

对于这两个调用,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; 
    }