为什么我的wcf应用程序不能使用和保存会话

本文关键字:保存 会话 不能 我的 wcf 应用程序 为什么 | 更新日期: 2023-09-27 18:18:53

下面是我的wcf应用程序的接口和类。首先,我想通过

在方法中获取sessionId

string sessionId=OperationContext.Current.SessionId

但是我发现sessionId总是空的。因此,我尝试使用并保存asp.net会话,如

HttpContext.Current.Session.Add("testSession", "testSession");

在一个方法中。在另一种方法中,我试图得到testSession,但它是空的。

var myTestSession= HttpContext.Current.Session["testSession"];

我的代码有什么问题?为什么SessionId总是为空?

我的wcf接口

[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface ITestSession
{
[OperationContract]
string SetSession(string sessionvalue);
[OperationContract]
string GetSession();
}

我的wcf类

 [AspNetCompatibilityRequirements(RequirementsMode =     AspNetCompatibilityRequirementsMode.Required)]
//[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class TestSession: ITestSession
{
 public string  SetSession(string sessionvalue)
 {
 HttpContext.Current.Session.Add("testSession", sessionvalue);
  return sessionvalue;
 }
 public   string  GetSession(string sessionvalue)
  {
  var testValue = HttpContext.Current.Session["testSession"];
    if (testValue ==null)
     return "null value";
     else
    return testValue;
     }
    }
  }

我尝试添加或删除配置,如<!--aspNetCompatibilityEnabled="true"-->,但仍然得到空会话。如何解决这个问题?

 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />       
  </system.serviceModel>

为什么我的wcf应用程序不能使用和保存会话

WCF会话与HTTP会话完全不同。它们被明确地打开和关闭。HttpContext不适用,因为WCF不一定是基于HTTP。

1)在WCF中管理会话,考虑管理您的服务的InstanceContextMode,看看这篇文章

2)如果我理解你有一个方法调用,将开始你的会话之前授权其他方法的调用,如果这是你的需要,你可以使用IsTerminating和isinitialization方法属性如下所述:

http://dadraraghu.wordpress.com/2010/12/20/setting-the-initialization-and-termination-of-the-wcf-session/

http://www.remondo.net/managing-wcf-session-lifetime-isinitiating-isterminating/