2013-05-30 33 views
2

我正在VS 2010中创建一个C#Web服务,以将数据从另一个软件程序传递给服务使用者。由于这里太复杂的原因,我写的Web服务应该记录会话生命周期中的一些信息。这些数据与其他软件程序相关联。 我已经把WebService类中的信息作为成员变量。我在另一个程序中创建了Webservice类的对象,并且保留了这些对象。不幸的是,Webservice对象中的数据不会超出当前函数的范围。这里是我有:ASMX Web服务的成员变量总是重新初始化

/* the Web service class */ 
public class Service1 : System.Web.Services.WebService 
{ 
    protected string _softwareID; 
    protected ArrayList _softwareList; 

    public Service1() 
    { 
     _softwareID= ""; 
     _softwareList = new ArrayList(); 
    } 

    [WebMethod] 
    public int WebServiceCall(int request) 
    { 
     _softwareID = request; 
     _softwareList.Add(request.ToString()); 
     return 1; 
    } 

    /* other Web methods */ 
} 

/* the form in the application that will call the Web service */ 
public partial class MainForm : Form 
{ 
    /* the service object */ 
    protected Service1 _service; 

    public MainForm() 
    { 
     InitializeComponent(); 
     _service = null; 
    } 

    private void startSoftware_Click(object sender, EventArgs e) 
    { 
     //initializing the service object 
     _service = new Service1(); 
     int results = _service.WebServiceCall(15); 
     /* etc., etc. */ 
    } 

    private void doSomethingElse_Click(object sender, EventArgs e) 
    { 
     if (_service == null) 
     { 
      /* blah, blah, blah */ 
      return; 
     } 
     //The value of service is not null 
     //However, the value of _softwareID will be a blank string 
     //and _softwareList will be an empty list 
     //It is as if the _service object is being re-initialized 
     bool retVal = _service.DoSomethingDifferent(); 
    } 
} 

我能做些什么来解决这个问题或做不同的工作呢? 在此先感谢任何人的帮助。我是品牌创建Web服务的新手。

+0

如果你发现你需要启用会话为您服务检查本文Ø ut http://www.asusoftware.com/ASP.NET-Tutorials/Managing-State-Web-Service.aspx – emd

+0

ASMX是一项传统技术,不应该用于新开发。 WCF应该用于Web服务客户端和服务器的所有新开发。一个暗示:微软已经在MSDN上退役了[ASMX Forum](http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/threads)。 –

+0

另外,为什么你仍然在使用'ArrayList'?从.NET 2.0开始已经过时了。 –

回答

2

假设您正在调用WebService,Service1将在每次调用期间使用默认构造函数进行初始化。这是设计的一部分。

如果您需要在方法调用之间保持数据,则需要以某种方式保存它,而不是更新类。

有几种方法可以做到这一点,而这是最好的取决于你的需要:

  • 数据库,可能是最安全的,并给出永久持久性
  • 静态字典,传递给每个呼叫键,或使用IP地址作为关键
  • HTTP Session对象(我​​不能确定这是如何与Web服务进行交互)
+1

为了启用会话,请将[WebMethod]属性更改为[WebMethod(EnableSession = true)],以查找要访问它的每种方法。 – Loophole