当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Create wcf web service with instanceContextMode = PerSession

问题描述:

I have a very simple service:

[ServiceContract]

public interface IPncService

{

[System.ServiceModel.Web.WebGet(UriTemplate = "set/{val}")]

[OperationContract]

bool SetVariable(string val);

[System.ServiceModel.Web.WebGet(UriTemplate = "get")]

[OperationContract]

string GetVariableVal();

}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]

public class PncService : IPncService

{

string someVariable;

public bool SetVariable(string val)

{

if (string.IsNullOrWhiteSpace(val))

return false;

else

{

someVariable = val;

return true;

}

}

public string GetVariableVal() {

return someVariable;

}

}

Why does the variable someVariable does not retain its value per session?

In other words if I do:

and then go to:

Why is the value of someVariable = null ? Is it a different session? I call that method on the same browser right after calling the set method...

网友答案:

You should have a read at this article : http://blogs.msdn.com/b/wenlong/archive/2010/02/21/using-asp-net-sessions-from-wcf.aspx

Short version :

WCF sessions are very different from ASP.NET Sessions. In short,

  • WCF sessions are represented as service instances (as CLR objects) and the states are part of each service instance. The sessions are initiated by the calling WCF client. WCF relies on special context to provide correlation for the sessions: sessionful channels, secure conversations, reliable-messaging, etc.
  • ASP.NET sessions are like shared data storage across different requests. The sessions are always initiated by the server. ASP.NET relies on cookies or special Uri goo to provide correlation for the sessions.

Thus :

Enabling Session States It is very straightforward to enable the ASP.NET session states. You only need to run WCF service in the ASP.NET Compatibility mode as being specified in the web.config:

分享给朋友:
您可能感兴趣的文章:
随机阅读: