我是 WCF 的新手,我创建了一个包含 DataContract 的服务,该服务应该保持数据成员状态,但是在我调用 getdata 后,我返回的状态为空。虽然当我使用 tcp 时,值是保留的。
[ServiceContract(Namespace = "http://KamiServiceHost.net/Go")]
public interface IService1
{
[OperationContract]
DataItem GetData();
[OperationContract]
void SaveData(DataItem item);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : IService1
{
private DataItem _item1;
private DataItem item
{
get { return _item1; }
set { _item1 = value; }
}
public void SaveData(DataItem setitem)
{
item = setitem;
}
public DataItem GetData()
{
return item;
}
}
主机 app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="Service.Service1" behaviorConfiguration="myServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000"/>
<add baseAddress="net.tcp://localhost:9000"/>
</baseAddresses>
</host>
<endpoint address="Service1" binding="basicHttpBinding" contract="Service.IService1"></endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="myServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
客户端代码:
client.Open();
var dataItem = new DataItem() { Name = "my object", Number = 12 };
client.SaveData(dataItem);
var data = client.GetData();
Console.WriteLine(string.Format("Name: {0} Number: {1}", data.Name, data.Number));
数据的值为空,我不知道为什么..任何帮助将不胜感激。
谢谢