WCF 中 使用 Session
1.标记WCF服务开启Session模式,使用SessionMode 来使Session有效化
[ServiceContract(SessionMode = SessionMode.Required)]
2.服务类添加ASPNETSESSION兼容标记
[System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Required)]
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
namespace Service
{
[ServiceContract (SessionMode = SessionMode .Required)]
[AspNetCompatibilityRequirements (RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode .Required)]
public partial class Service
{
}
}
3.配置WEB.CONFIG文件中<system.serviceModel>节
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true"></serviceHostingEnvironment>
<!-- WCF Siverlight 配置 -->
< system.serviceModel >
< behaviors >
< serviceBehaviors >
< behavior name = ".Service.ServiceBehavior ">
< serviceMetadata httpGetEnabled = "true " />
< serviceDebug includeExceptionDetailInFaults = "false " />
</ behavior >
</ serviceBehaviors >
</ behaviors >
< bindings >
< customBinding >
< binding name = "customBinding0 ">
< binaryMessageEncoding />
< httpTransport >
< extendedProtectionPolicy policyEnforcement = "Never " />
</ httpTransport >
</ binding >
</ customBinding >
</ bindings >
< serviceHostingEnvironment aspNetCompatibilityEnabled = "true " /> <!--这里配置-->
< services >
< service behaviorConfiguration = ".Service.ServiceBehavior " name = ".Service.Service ">
< endpoint address = "" binding = "customBinding " bindingConfiguration = "customBinding0 " contract = ".Service.Service " />
< endpoint address = "mex " binding = "mexHttpBinding " contract = "IMetadataExchange " />
</ service >
</ services >
</ system.serviceModel >
网络资源:
WCF状态保存分为两步:
(1) 使用SessionMode 来使Session有效化
- [ServiceContract(SessionMode
SessionMode=SessionMode.Required)] - public interface ICalculator
- {
- [OperationContract(IsOneWay=true)]
- void Adds(double x);
- [OperationContract]
- double GetResult();
- }
(2)ServiceBehavior 里面利用参数InstanceContextMode设定到底使用哪一种Session方式
- [ServiceBehavior(InstanceContextMode
InstanceContextMode=InstanceContextMode.PerCall)] - public class CalculatorService:ICalculator
- { }
WCF状态保存SessionMode 有三种值:
(1)Allowed
默认选值,允许但不强制使用Session
(2)Required 强制使用Session
(3)NotAllowed
不允许使用Session
WCF状态保存InstanceContextMode 有三种值:
(1) Percall
为user的每一次调用生成一个SessionID
生命周期:调用开始 ---->调用结束,这种情况和不使用Session是一样的
(2)
PerSession 为每个用户生成一个SessionID
生命周期:客户端代理生成--->客户端代理关闭
和最原先的Session是一样的
(3) Seigle 生成唯一的SessionID,所有的用户共享
从host创建---->host 关闭,和Application 一样
在 Silverlight中使用SESSION
首先Session是运行在服务器上的,而Silverlight运行在客户端。因此在Silverlight中使用SESSION的说法并不准 确,
只因大家经常这样搜索才起这个名字。
有两种方法实现Silverlight与Session的关联:
方法一、通过WCF使用ASP.NET中的Session[因BasicHttpBinding不支持WCF中的Session,如使用WCF会话 将报错 ]
首先:在web.config中<system.serviceModel >下添加:
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
然后:在服务类[不是接口]下添加如下属性:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
接下来就可以使用Session记得添加System.Web的引用
HttpContext.Current.Session["YourName"] = something;
object something = HttpContext.Current.Session["YourName"];
方法二、在客户端新建一个静态类模拟Session
如要保存登陆信息,可在验证了用户名、密码之后在客户端保存相关信息。
using System;
using System.Collections.Generic;
namespace
SessionDemo
{
public static class SessionManager
{
private
static Dictionary<string, object> session = new
Dictionary<string, object>();
public static
Dictionary<string, object> Session
{
get { return
SessionManager.session; }
set { SessionManager.session = value; }
}
}
}
使用方法:
赋值:
SessionManager.Session["uname"] = "kunal";
取值:
txbUname.Text
= SessionManager.Session["uname"].ToString();
介绍
WCF(Windows Communication Foundation) - 会话状态:
ServiceContract
·SessionMode.Allowed - 指定当传入绑定支持会话时,协定也支持会话(默认值)
·SessionMode.Required - 指定协定需要会话绑定。如果绑定并未配置为支持会话,则将引发异常
·SessionMode.NotAllowed - 指定协定永不支持启动会话的绑定
OperationContract
·IsInitiating - 获取或设置一个值,该值指示方法是否实现可在服务器上启动会话(如果存在会话)的操作。
·IsTerminating - 获取或设置一个值,该值指示服务操作在发送答复消息(如果存在)后,是否会导致服务器关闭会话。
示例
1、服务
IHello.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace WCF.ServiceLib.SessionManagement
{
/**//// <summary>
/// 演示会话状态的接口
/// </summary>NotAllowed
/// <remarks>
/// SessionMode - 获取或设置是否允许、不允许或要求会话
/// SessionMode.Allowed - 指定当传入绑定支持会话时,协定也支持会话(默认值)
/// SessionMode.Required - 指定协定需要会话绑定。如果绑定并未配置为支持会话,则将引发异常
/// SessionMode.NotAllowed - 指定协定永不支持启动会话的绑定
/// </remarks>
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IHello
{
/**//// <summary>
/// 初始化Session
/// </summary>
/// <remarks>
/// IsInitiating - 获取或设置一个值,该值指示方法是否实现可在服务器上启动会话(如果存在会话)的操作。
/// IsTerminating - 获取或设置一个值,该值指示服务操作在发送答复消息(如果存在)后,是否会导致服务器关闭会话。
/// </remarks>
[OperationContract(IsInitiating = true, IsTerminating = false)]
void StartSession();
/**//// <summary>
/// 结束Session
/// </summary>
[OperationContract(IsInitiating = false, IsTerminating = true)]
void StopSession();
/**//// <summary>
/// 获取计数器结果
/// </summary>
/// <returns></returns>
[OperationContract(IsInitiating = false, IsTerminating = false)]
int Counter();
/**//// <summary>
/// 获取SessionId
/// </summary>
/// <returns></returns>
[OperationContract(IsInitiating = false, IsTerminating = false)]
string GetSessionId();
}
}
Hello.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace WCF.ServiceLib.SessionManagement
{
/**//// <summary>
/// 演示会话状态的接口
/// </summary>
/// <remarks>
/// InstanceContextMode - 获取或设置指示新服务对象何时创建的值。
/// InstanceContextMode.PerSession - 为每个会话创建一个新的 System.ServiceModel.InstanceContext 对象。
/// InstanceContextMode 的默认值为 InstanceContextMode.PerSession
/// </remarks>
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Hello : IHello
{
private int _counter;
/**//// <summary>
/// 初始化Session
/// </summary>
public void StartSession()
{
_counter = 0;
}
/**//// <summary>
/// 结束Session
/// </summary>
public void StopSession()
{
_counter = 0;
}
/**//// <summary>
/// 获取计数器结果
/// </summary>
/// <returns></returns>
public int Counter()
{
_counter++;
return _counter;
}
/**//// <summary>
/// 获取SessionId
/// </summary>
/// <returns></returns>
public string GetSessionId()
{
return OperationContext.Current.SessionId;
}
}
}
2、宿主
Hello.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WCF.ServiceLib.SessionManagement.Hello" %>
Web.config
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="SessionManagementBehavior">
<!--httpGetEnabled - 使用get方式提供服务-->
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<!--name - 提供服务的类名-->
<!--behaviorConfiguration - 指定相关的行为配置-->
<service name="WCF.ServiceLib.SessionManagement.Hello" behaviorConfiguration="SessionManagementBehavior">
<!--address - 服务地址-->
<!--binding - 通信方式-->
<!--contract - 服务契约-->
<!--bindingConfiguration - 指定相关的绑定配置-->
<endpoint address="" binding="wsHttpBinding" contract="WCF.ServiceLib.SessionManagement.IHello" bindingConfiguration="SessionManagementBindingConfiguration"/>
</service>
</services>
<bindings>
<wsHttpBinding>
<!--wsHttpBinding 可提供 安全会话 和 可靠会话-->
<!--receiveTimeout - 在传输引发异常之前可用于完成读取操作的时间间隔(此处可认为是Session过期时间)-->
<binding name="SessionManagementBindingConfiguration" receiveTimeout="00:00:10">
<!--指示是否在通道终结点之间建立 WS-RM (WS-ReliableMessaging) 可靠会话。默认值为 false。-->
<reliableSession enabled="true"/>
<security>
<!--此属性控制安全上下文令牌是否通过客户端与服务之间的 WS-SecureConversation 交换建立。将它设置为 true 要求远程方支持 WS-SecureConversation。-->
<message establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
3、客户端
Hello.aspx
<%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Hello.aspx.cs"
Inherits="InstanceMode_Hello" Title="会话状态(Session)" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Button ID="btnStartSession" runat="server" Text="StartSession" OnClick="btnStartSession_Click" /> <asp:Button ID="btnCounter" runat="server" Text="Counter" OnClick="btnCounter_Click" /> <asp:Button ID="btnGetSessionId" runat="server" Text="GetSessionId" OnClick="btnGetSessionId_Click" /> <asp:Button ID="btnStopSession" runat="server" Text="StopSession" OnClick="btnStopSession_Click" />
</asp:Content>
Hello.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class InstanceMode_Hello : System.Web.UI.Page
{
SessionManagemenSvc.HelloClient _proxy = null;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["proxy"] == null)
Session["proxy"] = new SessionManagemenSvc.HelloClient();
_proxy = Session["proxy"] as SessionManagemenSvc.HelloClient;
}
protected void btnStartSession_Click(object sender, EventArgs e)
{
_proxy.StartSession();
}
protected void btnCounter_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"js",
string.Format("alert('计数器:{0}')", _proxy.Counter()),
true);
}
protected void btnGetSessionId_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"js",
string.Format("alert('SessionId:{0}')", _proxy.GetSessionId()),
true);
}
protected void btnStopSession_Click(object sender, EventArgs e)
{
_proxy.StopSession();
}
}
Web.config
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<client>
<!--address - 服务地址-->
<!--binding - 通信方式-->
<!--contract - 服务契约-->
<!--bindingConfiguration - 指定相关的绑定配置-->
<endpoint address="http://localhost:3502/ServiceHost/SessionManagement/Hello.svc " binding="wsHttpBinding" contract="SessionManagemenSvc.IHello" bindingConfiguration="SessionManagementBindingConfiguration" />
</client>
<bindings>
<wsHttpBinding>
<binding name="SessionManagementBindingConfiguration">
<!--指示是否在通道终结点之间建立 WS-RM (WS-ReliableMessaging) 可靠会话。默认值为 false。-->
<reliableSession enabled="true"/>
<security>
<!--此属性控制安全上下文令牌是否通过客户端与服务之间的 WS-SecureConversation 交换建立。将它设置为 true 要求远程方支持 WS-SecureConversation。-->
<message establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
运行结果:
单击"btnStartSession"按钮,初始化Session
单击"btnCounter"按钮,Session级别的计数器累加
单击"btnGetSessionId"按钮,获取当前Session的SessionId
单击"btnStopSession"按钮,终止Session
注:
Host中的wsHttpBinding配置的receiveTimeout属性为Session的过期时间