WCF会话ID随每次调用而变化

时间:2013-11-20 22:52:54

标签: c# wcf sessionid wshttpbinding

我正在尝试在调用WCF服务之间跟踪和使用会话ID但是在同一个WCF客户端实例的每次调用之后,我会收到两个不同的会话ID。

这是服务合同,指定需要会话:

[ServiceContract(SessionMode=SessionMode.Required)]
public interface IMonkeyService
{
    [OperationContract(ProtectionLevel=System.Net.Security.ProtectionLevel.None, IsOneWay = true, IsInitiating = true, IsTerminating = false)]
    void Init();

    [OperationContract(ProtectionLevel = System.Net.Security.ProtectionLevel.None, IsOneWay = false, IsInitiating = false, IsTerminating = false)]
    string WhereAreMyMonkies();

    [OperationContract(ProtectionLevel = System.Net.Security.ProtectionLevel.None, IsOneWay = true, IsInitiating = false, IsTerminating = true)]
    void End();
}

以下是服务实施:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, IncludeExceptionDetailInFaults=true)]
public class BestMonkeyService : IMonkeyService
{
    public void Init() { ;}
    public void End() { ;}
    public string WhereAreMyMonkies()
    {
        return "Right here";
    }
}

以下是正在打开的服务:

_Service = new ServiceHost(typeof(BestMonkeyService));
var binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.None;
binding.ReliableSession.Enabled = true;
string uriAddress = "http://localhost:8000/MONKEY_SERVICE";
var endpoint = _Service.AddServiceEndpoint(typeof(IMonkeyService), binding, uriAddress);
_Service.Open();

这是客户端配置

<system.serviceModel>
 <client>
  <endpoint address="http://localhost:8000/MONKEY_SERVICE" bindingConfiguration="wsHttpBindingConfiguration"
            binding="wsHttpBinding" contract="IMonkeyService" />
 </client>
 <bindings>
  <wsHttpBinding>
   <binding name="wsHttpBindingConfiguration">
    <security mode="None" />
    <reliableSession enabled="true" />
   </binding>
  </wsHttpBinding>
 </bindings>
</system.serviceModel>

客户在第一次通话后保持打开的电话:

var client = new MonkeyClient();
client.Init();
client.WhereAreMyMonkies();
client.WhereAreMyMonkies();
client.End();

我收到一个ActionNotSupportedException

The message with Action 'http://tempuri.org/IMonkeyService/WhereAreMyMonkies' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).

我使用相同的绑定和安全性配置了服务和客户端。我错过了什么?

2 个答案:

答案 0 :(得分:0)

正如here所解释的那样,因为IsInitiating参数的默认值为true,您的每个调用都会启动一个新会话。

你需要这样的东西:

[OperationContract(IsInitiating=false, IsTerminating=false)]
string WhereAreMyMonkies();

默认情况下,会话在通道打开时启动。您还可以添加显式创建和终止会话的方法(如documentation中所述)。

答案 1 :(得分:0)

WSHttpBinding不支持没有可靠消息传递或安全会话的会话。

查看How to enable Session with SSL wsHttpBinding in WCF

的答案