我正在将客户端发送的对象添加到服务中的列表,我的问题是这样,在调试期间我看到,只要我从主服务返回到客户端,列表就会变为0。&# 39; s就像列表被清空一样,一旦程序流程返回到客户端,然后当客户端向服务发送数据时数据就在那里,一旦我输入服务方法,列表就会被填充用旧数据。我想从程序的另一部分访问这些数据,但我总是看到列表为空。有什么提示吗?
答案 0 :(得分:0)
根据我的评论,您需要设置ServiceContract
' SessionMode
以及ServiceBehavior
' InstanceContextMode
。默认InstanceContextMode
为PerCall
,这意味着您的列表不会被保留。您需要将其更改为使用PerSession
。请参阅下面的完整工作示例(.NET 4):
服务端代码:
using System.Collections.Generic;
using System.ServiceModel;
namespace WcfService1
{
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IService1
{
[OperationContract]
int AddData(string data);
[OperationContract]
List<string> GetData();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : IService1
{
private readonly List<string> _myList = new List<string>();
public int AddData(string data)
{
_myList.Add(data);
return _myList.Count;
}
public List<string> GetData()
{
return _myList;
}
}
}
服务端web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="wsHttpBinding"/>
</protocolMapping>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
客户端:
using System;
using System.Collections.Generic;
using ConsoleApplication1.ServiceReference1;
namespace ConsoleApplication1
{
internal class Program
{
private static void Main()
{
using (var service = new Service1Client())
{
// Add items...
int itemCount;
itemCount = service.AddData("Test Item 1");
Console.WriteLine("Service now holds {0} items", itemCount);
itemCount = service.AddData("Test Item 2");
Console.WriteLine("Service now holds {0} items", itemCount);
itemCount = service.AddData("Test Item 3");
Console.WriteLine("Service now holds {0} items", itemCount);
// Get all of the items added...
List<string> listFromService = service.GetData();
foreach (var listItem in listFromService)
{
Console.WriteLine(" * {0}", listItem);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
客户端app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IService1" />
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:59604/Service1.svc" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
name="WSHttpBinding_IService1">
</endpoint>
</client>
</system.serviceModel>
</configuration>
注意:我必须确保wsHttpBinding
被basicHttpBinding
用作 NOT 支持会话。