我在服务端有如下配置
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
<sessionState cookieless="UseCookies" mode="InProc"/>
</system.web>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="ws">
<security mode="None" />
<reliableSession enabled="true" />
</binding>
</wsHttpBinding>
</bindings>
<services>
<service name="WCFSvc.WCFSvc">
<endpoint name="endPoint1"
address="http://localhost:60219/Service1.svc"
binding="wsHttpBinding" bindingConfiguration="ws"
contract="WCFSvc.IWCFSvc" />
</service>
</services>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="false" >
如您所见,我正在使用 aspNetCompatibilityEnabled="true"
。我正在使用启用了可靠 session 的 wsHttpBinding
。
在客户端我也启用了 cookies
我的InstanceContextMode
是PerSession
,服务契约上的 session 模式是SessionMode = SessionMode.Required
并发模式为单
我有一个操作契约(Contract),其中 IsInitiating
属性设置为 true,而对于其他操作契约(Contract),我明确将它们设置为 false,因为默认设置为 true(我认为这是问题所在,但不是! !!)
有了这一切,我只能实现 WCF 级别的 session 。即 OperationContext.Current.Session ID
在对服务的不同调用之间保持相同,但 HttpContext.Current.Session.SessionID
对每个请求保持变化!
但是我想使用 ASP.NET 兼容模式来利用 ASP.NET session ,为此我需要 HttpContext.Current.Session.SessionID
对于单个 session 中的连续请求是相同的.
那么,我还应该做些什么来实现这一点?
最佳答案
结果是浏览器不存在! ASP.NET 正在设置 session ID,但浏览器的工作是在每个后续请求的请求 header 中发送相同的 session ID。 WCF 客户端不会这样做。因此,我们为每个新请求获得一个新的 session ID。
因此,修复方法是在每个请求中手动设置从 ASP.NET 响应中发送的 session ID。我们如何做到这一点?我们在 OutgoingMessageProperties
中这样设置它...
HttpResponseMessageProperty responseProperty = OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name]
as HttpResponseMessageProperty;
HttpSessionCookieHelper helper = HttpSessionCookieHelper.Create((string)responseProperty.Headers[HttpResponseHeader.SetCookie]);
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
helper.AddSessionIdToRequest(requestProperty);
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
有关HttpSessionCookieHelper
类的代码和更多信息,请参阅Marcel 提到的博客here
关于c# - 在 WCF 中利用 ASP.NET session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25455006/