InstanceContextMode = InstanceContextMode.PerSession无法正常运行

时间:2018-12-09 12:00:06

标签: c# wcf

我是WCF的新手,我编写了一个使用InstanceContextMode的示例WCF服务。当我使用PerSession时,我的计数器值不会增加。为什么不为每个服务调用使用相同的实例。 以下是我的代码

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : IService1
{
    int count;
    public int Add(int a, int b)
    {
        count++;
        return a + b;
    }

    public int GetCount()
    {
        return count;
    }
}

WebConfig

<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

Client.cs

DemoWCFService.Service1Client client = new DemoWCFService.Service1Client();
        Console.WriteLine(""+ client.Add(10,20));
        Console.WriteLine("" + client.Add(10, 20));
        Console.WriteLine("" + client.Add(10, 20));

        Console.WriteLine("" + client.GetCount());
        Console.ReadKey();

请帮助我。

1 个答案:

答案 0 :(得分:0)

BasicHttpBinding不支持PerSession。 最好使用支持会话的绑定,例如WSHttpBinding,WS2007HttpBinding。

为确保使用支持会话的绑定,可以使用服务行为

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

如果您的绑定不支持会话,则会导致错误。