---
title: "[原创]WCF技术剖析之五：利用ASP.NET兼容模式创建支持会话（Session）的WCF服务"
author: "varsoft"
date: "2009-06-25T18:10:00Z"
tags: []
slug: "wcf-asp-net-session-wcf"
draft: false
lastmod: "2009-06-25T18:10:00Z"
id: 871307
url: "https://varsoft.iteye.com/blog/871307"
---

在《[基于IIS的WCF服务寄宿（Hosting）实现揭秘](http://www.cnblogs.com/artech/archive/2009/06/24/1510497.html)》中，我们谈到在采用基于IIS（或者说基于ASP.NET）的WCF服务寄宿中，具有两种截然不同的运行模式：ASP.NET并行（Side by Side）模式和ASP.NET兼容模式。对于前者，WCF通过HttpModule实现了服务的寄宿，而对于后者，WCF的服务寄宿通过一个HttpHandler实现。只有在ASP.NET兼容模式下，我们熟悉的一些ASP.NET机制才能被我们使用，比如通过HttpContext的请求下下文；基于文件或者Url的授权；HttpModule扩展；身份模拟（Impersonation）等。

由于在ASP.NET兼容模式下，ASP.NET采用与.aspx Page完全一样的方式处理基于.svc的请求，换言之，我们就可以借助当前HttpContext的SessionState维护会话状态，进而创建一个支持会话的WCF Service。接下来，我们就通过一个简单的例子，一步步地创建这样的会话服务。本案例采用如**图1**所示的3层结构。 （Source Code从[这里](http://files.cnblogs.com/artech/Artech.AspCompatibleServices.zip)下载）

[](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/41d1108a4667_100D4/clip_image002_2.jpg)

[![clip_image002](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/41d1108a4667_100D4/clip_image002_thumb.jpg "clip_image002")](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/41d1108a4667_100D4/clip_image002_2.jpg)

[**图1 ASP.NET兼容模式案例应用结构**  
\
**步骤一、定义服务契约：ICalculator**  
\
案例依然沿用计算服务的例子，不过通过原来直接与传入操作数并得到运算结果的方式不同，为了体现会话状态的存在，我们将本案例的WCF服务定义成“累积计算服务”：保留上一次运算的结果，并将其作为后续运算的操作数。为此，定义了如下一个接口作为服务契约：前面4个操作代表基本的加、减、乘、除运算，计算结果通过GetResult方法获得。  
\
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } &lt;/style&gt;  
\
`1: using System.ServiceModel;` &lt;!--CRLF--&gt;`2: namespace Artech.AspCompatibleServices.Contracts` &lt;!--CRLF--&gt;`3: {` &lt;!--CRLF--&gt;`4: [ServiceContract]` &lt;!--CRLF--&gt;`5: public interface ICalculator` &lt;!--CRLF--&gt;`6: {` &lt;!--CRLF--&gt;`7: [OperationContract]` &lt;!--CRLF--&gt;`8: void Add(double x);` &lt;!--CRLF--&gt;`9: [OperationContract]` &lt;!--CRLF--&gt;`10: void Subtract(double x);` &lt;!--CRLF--&gt;`11: [OperationContract]` &lt;!--CRLF--&gt;`12: void Multiply(double x);` &lt;!--CRLF--&gt;`13: [OperationContract]` &lt;!--CRLF--&gt;`14: void Divide(double x);` &lt;!--CRLF--&gt;`15: [OperationContract]` &lt;!--CRLF--&gt;`16: double GetResult();` &lt;!--CRLF--&gt;`17: }` &lt;!--CRLF--&gt;`18: }` &lt;!--CRLF--&gt;  
\
**步骤二、实现服务：CalculatorService**  
\
服务的实现和.svc都定义在一个ASP.NET Web站点项目中。对于定义在 CalculatorService中的每次运算，先通过HttpContext从SessionState中取出上一次运算的结果，完成运算后再将新的运算结果保存到SessionState中。通过在CalculatorService上应用AspNetCompatibilityRequirementsAttribute实现对ASP.NET兼容模式的支持。  
\
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } &lt;/style&gt;  
\
`1: using System.ServiceModel.Activation;` &lt;!--CRLF--&gt;`2: using System.Web;` &lt;!--CRLF--&gt;`3: using Artech.AspCompatibleServices.Contracts;` &lt;!--CRLF--&gt;`4: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]` &lt;!--CRLF--&gt;`5: public class CalculatorService : ICalculator` &lt;!--CRLF--&gt;`6: {` &lt;!--CRLF--&gt;`7: public void Add(double x)` &lt;!--CRLF--&gt;`8: {` &lt;!--CRLF--&gt;`9: HttpContext.Current.Session["__Result"] = GetResult() + x;` &lt;!--CRLF--&gt;`10: }` &lt;!--CRLF--&gt;`11: public void Subtract(double x)` &lt;!--CRLF--&gt;`12: {` &lt;!--CRLF--&gt;`13: HttpContext.Current.Session["__Result"] = GetResult() - x;` &lt;!--CRLF--&gt;`14: }` &lt;!--CRLF--&gt;`15: public void Multiply(double x)` &lt;!--CRLF--&gt;`16: {` &lt;!--CRLF--&gt;`17: HttpContext.Current.Session["__Result"] = GetResult() * x;` &lt;!--CRLF--&gt;`18: }` &lt;!--CRLF--&gt;`19: public void Divide(double x)` &lt;!--CRLF--&gt;`20: {` &lt;!--CRLF--&gt;`21: HttpContext.Current.Session["__Result"] = GetResult() / x;` &lt;!--CRLF--&gt;`22: }` &lt;!--CRLF--&gt;`23: public double GetResult()` &lt;!--CRLF--&gt;`24: {` &lt;!--CRLF--&gt;`25: if (HttpContext.Current.Session["__Result"] == null)` &lt;!--CRLF--&gt;`26: {` &lt;!--CRLF--&gt;`27: HttpContext.Current.Session["__Result"] = 0.0;` &lt;!--CRLF--&gt;`28: }` &lt;!--CRLF--&gt;`29: return (double)HttpContext.Current.Session["__Result"];` &lt;!--CRLF--&gt;`30: }` &lt;!--CRLF--&gt;`31: }` &lt;!--CRLF--&gt;  
\
下面是CalculatorService对应的.svc的定义和Web.config。为了简洁，在&lt;@ServiceHost%&gt;指令中，仅仅设置一个必需属性Service。对于ASP.NET兼容模式的支持，配置&lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true"/&gt;必不可少。  
\
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } &lt;/style&gt;  
\
`1: <?xml version="1.0"?>` &lt;!--CRLF--&gt;`2: <configuration>` &lt;!--CRLF--&gt;`3: <system.serviceModel>` &lt;!--CRLF--&gt;`4: <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>` &lt;!--CRLF--&gt;`5: <services>` &lt;!--CRLF--&gt;`6: <service name="CalculatorService">` &lt;!--CRLF--&gt;`7: <endpoint binding="wsHttpBinding" contract="Artech.AspCompatibleServices.Contracts.ICalculator" />` &lt;!--CRLF--&gt;`8: </service>` &lt;!--CRLF--&gt;`9: </services>` &lt;!--CRLF--&gt;`10: </system.serviceModel>` &lt;!--CRLF--&gt;`11: </configuration>` &lt;!--CRLF--&gt;  
\
**步骤三、创建客户端：Client**  
\
CalculatorService的客户端应用通过一个Console应用程序模拟，其服务调用方式并无特别之处，下面是相关的代码和配置。  
\
`1: using System;` &lt;!--CRLF--&gt;`2: using System.ServiceModel;` &lt;!--CRLF--&gt;`3: using Artech.AspCompatibleServices.Contracts;` &lt;!--CRLF--&gt;`4: namespace Artech.AspCompatibleServices.Clients` &lt;!--CRLF--&gt;`5: {` &lt;!--CRLF--&gt;`6: class Program` &lt;!--CRLF--&gt;`7: {` &lt;!--CRLF--&gt;`8: static void Main(string[] args)` &lt;!--CRLF--&gt;`9: {` &lt;!--CRLF--&gt;`10: using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>("CalculatorService"))` &lt;!--CRLF--&gt;`11: {` &lt;!--CRLF--&gt;`12: ICalculator proxy = channelFactory.CreateChannel();` &lt;!--CRLF--&gt;`13: Console.WriteLine("初始值为: {0}", proxy.GetResult()); proxy.Add(1);` &lt;!--CRLF--&gt;`14: Console.WriteLine("Add(3)", proxy.GetResult());` &lt;!--CRLF--&gt;`15: Console.WriteLine("运算结果为: {0}", proxy.GetResult()); proxy.Multiply(10);` &lt;!--CRLF--&gt;`16: Console.WriteLine("Multiply(10)", proxy.GetResult()); Console.WriteLine("运算结果为: {0}", proxy.GetResult()); proxy.Subtract(2);` &lt;!--CRLF--&gt;`17: Console.WriteLine("Subtract(2)", proxy.GetResult()); Console.WriteLine("运算结果为: {0}", proxy.GetResult());` &lt;!--CRLF--&gt;`18: } Console.Read();` &lt;!--CRLF--&gt;`19: }` &lt;!--CRLF--&gt;`20: }` &lt;!--CRLF--&gt;`21: }` &lt;!--CRLF--&gt;  
\
`1: <?xml version="1.0" encoding="utf-8" ?>` &lt;!--CRLF--&gt;`2: <configuration>` &lt;!--CRLF--&gt;`3: <system.serviceModel>` &lt;!--CRLF--&gt;`4: <client>` &lt;!--CRLF--&gt;`5: <endpoint address="http://localhost/AspCompatibleServices/CalculatorService.svc"` &lt;!--CRLF--&gt;`6: binding="wsHttpBinding" contract="Artech.AspCompatibleServices.Contracts.ICalculator"` &lt;!--CRLF--&gt;`7: name="CalculatorService"/>` &lt;!--CRLF--&gt;`8: </client> </system.serviceModel>` &lt;!--CRLF--&gt;`9: </configuration>` &lt;!--CRLF--&gt;  
\
但是，但我们运行客户端的程序，输出的结果并不像我们希望的那样。从下面的结果可以看出，每次通过GetResult（）方法得到的结果都是0，也就是说，服务端并没有将运算结果保存下来。  
\
`1: 初始值为：0` &lt;!--CRLF--&gt;`2: Add（3）运算结果为：0` &lt;!--CRLF--&gt;`3: Multiply（10）运算结果为：0` &lt;!--CRLF--&gt;`4: Subtract（2）运算结果为：0` &lt;!--CRLF--&gt;  
\
**允许Cookie传递**  
\
要解释这个问题，得从Session的实现机制说起。众所周知，HTTP是无状态（Stateless）的传输协议，对服务端来说，它收到的每个HTTP请求都是全新的请求。ASP.NET会话（Session）的实现很简单，就是让每次HTTP请求携带Session的识别信息（Session ID），那么服务就可以根据此信息判断请求来自哪个客户端了。关于Session识别信息的保存，ASP.NET有两种方式：Cookie和URL，前者将其放到Cookie中，每次HTTP请求将会携带该Cookie的值，后者则将其作为请求URL的一部分。一般情况下采用基于Cookie的实现机制，如果Cookie禁用则采用后者。  
\
那么对于ASP.NET兼容模式下的WCF也一样，要想让服务端能够识别会话，就需要让每个服务调用的HTTP请求携带Session的识别信息，我们也可以通过传递Cookie的方式来解决这个问题。对于WCF来说，Cookie传递能够通过Binding来控制，对于WsHttpBinding来说，默认情况下并不允许Cookie的传递。我们可以通过WsHttpBinding的AllowCookies来控制是否允许传递Cookie，该属性可以通过配置进行设置。为此，我们对客户端的配置进行了如下的修改。再次运行我们的案例程序，将会得到你期望的输出。  
\
&lt;style type="text/css"&gt;.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /\*white-space: pre;\*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .cs](http://images.cnblogs.com/cnblogs_com/artech/WindowsLiveWriter/41d1108a4667_100D4/clip_image002_2.jpg)