WCF会话Id随每次调用而更改



我试图在对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).

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

正如这里所解释的,因为IsInitiating参数的默认值是true,所以您的每个调用都启动了一个新会话。

你需要这样的东西:

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

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

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

请参阅"如何在WCF 中使用SSL启用会话"的答案

最新更新