You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在IIS中托管WCF Service时遇Session相关异常求助

问题分析与解决方案

这个异常的核心原因是服务契约的会话要求与当前绑定的会话支持能力不匹配:BasicHttpBinding默认不支持强制会话(SessionMode.Required),但你的服务契约明确要求使用会话,导致绑定无法满足契约的要求,触发InvalidOperationException。

以下是具体的解决办法:

1. 调整服务契约,取消会话依赖

如果你的服务不需要会话功能,直接修改契约的SessionMode属性,将其设置为NotAllowed或Allowed:

[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface IYourWcfService
{
    [OperationContract]
    string SampleMethod();
}

这样契约不再强制要求会话,BasicHttpBinding就能正常工作。

2. 更换为支持会话的绑定

如果服务确实需要会话功能,替换BasicHttpBinding为原生支持会话的绑定,比如WSHttpBinding或NetTcpBinding。以WSHttpBinding为例,修改web.config的服务配置:

<system.serviceModel>
  <bindings>
    <wsHttpBinding>
      <binding name="WSHttpSessionBinding">
        <!-- 启用可靠会话,按需配置 -->
        <reliableSession enabled="true" inactivityTimeout="00:10:00" />
      </binding>
    </wsHttpBinding>
  </bindings>
  <services>
    <service name="YourNamespace.YourWcfService">
      <endpoint 
          address="" 
          binding="wsHttpBinding" 
          bindingConfiguration="WSHttpSessionBinding" 
          contract="YourNamespace.IYourWcfService" />
    </service>
  </services>
</system.serviceModel>

WSHttpBinding默认支持会话,配合reliableSession可实现可靠的会话机制。

3. 配置BasicHttpBinding启用Cookie-based会话(不推荐)

BasicHttpBinding本身是无状态的HTTP绑定,仅支持基于Cookie的弱会话,且不能满足SessionMode.Required的强制要求。如果必须使用BasicHttpBinding,可按以下配置:

  1. 修改web.config的绑定配置,开启Cookie支持:
<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="BasicHttpCookieSession" allowCookies="true">
      </binding>
    </basicHttpBinding>
  </bindings>
  <services>
    <service name="YourNamespace.YourWcfService">
      <endpoint 
          address="" 
          binding="basicHttpBinding" 
          bindingConfiguration="BasicHttpCookieSession" 
          contract="YourNamespace.IYourWcfService" />
    </service>
  </services>
</system.serviceModel>
  1. 同时将契约的SessionMode改为Allowed(不能是Required):
[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface IYourWcfService
{
    [OperationContract]
    string SampleMethod();
}

这种方式仅能实现简单的Cookie会话,不适合需要可靠会话的场景。

内容的提问来源于stack exchange,提问作者phpain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:30:46