C# 始终重新初始化ASMX Web服务的成员变量
我在VS2010中创建了一个C#Web服务,将数据从另一个软件程序传递给服务消费者。由于过于复杂的原因,我编写的Web服务应该在会话期间跟踪一些信息。该数据与其他软件程序相关联。 我已将信息作为成员变量放入WebService类中。我在另一个程序中创建了Webservice类的对象,并保留了这些对象。不幸的是,Webservice对象中的数据不会持续超过当前函数的范围。以下是我所拥有的:C# 始终重新初始化ASMX Web服务的成员变量,c#,web-services,asmx,C#,Web Services,Asmx,我在VS2010中创建了一个C#Web服务,将数据从另一个软件程序传递给服务消费者。由于过于复杂的原因,我编写的Web服务应该在会话期间跟踪一些信息。该数据与其他软件程序相关联。 我已将信息作为成员变量放入WebService类中。我在另一个程序中创建了Webservice类的对象,并保留了这些对象。不幸的是,Webservice对象中的数据不会持续超过当前函数的范围。以下是我所拥有的: /* the Web service class */ public class Service1 : Sy
/* 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服务一无所知。假设您正在调用Web服务,
Service1将在每次调用期间使用默认构造函数初始化。这是设计的一部分
如果需要在方法调用之间持久化数据,则需要以更新类以外的方式持久化数据
有几种方法可以做到这一点,哪种方法最好取决于您的需要:
- 数据库,可能是最安全的,并提供永久的持久性
- 向每个调用传递密钥或使用IP地址作为密钥的静态字典
- HTTP会话对象(我不确定它如何与Web服务交互)
如果您发现需要为您的服务启用会话,请查看本文ASMX是一种遗留技术,不应用于新的开发。WCF应用于web服务客户端和服务器的所有新开发。一个提示:微软已经停用了MSDN上的。另外,你为什么还在使用ArrayList
?自.NET 2.0以来,它已过时。为了启用会话,请将要访问它的每个方法的[WebMethod]属性更改为[WebMethod(EnableSession=true)]。