2012-11-25 77 views
2

我创建了我的WCF服务,它与SQL Server建立连接并返回查询结果。WCF会话和连接到数据库

我的问题是:如何保存来自客户端的请求,而不是为来自客户端的每个请求建立连接?

我想要的场景是:

  1. 在客户端输入用户和SQL Server的密码,使服务器上的连接(我需要对数据进行加密?)
  2. 保持会话持续30秒。

感谢

+2

您需要使用**每会话**激活模型的WCF - 请参阅[本Codeproject文章](http://www.codeproject.com/Articles/86007/3-ways-to-do-WCF-instance-management -Per-call-Per)或[此MSDN杂志文章](http://msdn.microsoft.com/zh-cn/magazine/cc163590.aspx) –

回答

0

连接到SQL Server是由客户端缓存。假设您使用HTTPS来保护传输,那么您应该让客户端根据每个请求发送凭证。假设您编写了相同的连接字符串,您可能会使用缓存连接。

老实说,我会避免尝试在会话中捕获它;然而,这也是可能的。客户端 - 服务器协议应尽可能保持无状态。

如果您没有使用HTTPS,那么您完全没有安全感,您也可以一并删除密码要求,并允许任何人查询他们想要的任何数据。

1

http://msdn.microsoft.com/en-us/magazine/cc163590.aspx,您可以使用每会话服务

[AttributeUsage(AttributeTargets.Interface|AttributeTargets.Class, Inherited=false)] 
public sealed class ServiceContractAttribute : Attribute 
{ 
    public bool Session {get;set;} 
    ... // More members 
} 

会话默认为false。为了支持会话,你需要会话在合同级别设置为true: [的ServiceContract(会话=真)] 接口IMyContract {...}

要完成配置,您需要指示Windows通信基金会保持服务实例在整个会话期间保持活动状态,并将客户端消息定向到它。这种局部行为方面通过设置ServiceBehavior属性InstanceContextMode.PerSession的InstanceContextMode财产在下面的实现,如图所示:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
class MyService : IMyContract {...} 

每会话服务和ClientService代码

[ServiceContract(Session = true)] 
interface IMyContract 
{ 
    [OperationContract] 
    void MyMethod(); 
} 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
class MyService : IMyContract,IDisposable 
{ 
    int m_Counter = 0; 
    MyService() 
    { 
     Trace.WriteLine("MyService.MyService()"); 
    } 
    public void MyMethod() 
    { 
     m_Counter++; 
     Trace.WriteLine("Counter = " + m_Counter); 
    } 
    public void Dispose() 
    { 
     Trace.WriteLine("MyService.Dispose()"); 
    } 
} 

客户代码

MyContractProxy proxy = new MyContractProxy(); 
proxy.MyMethod(); proxy.MyMethod(); 
proxy.Close(); 

c并且该服务可以通过在绑定中设置不同的值来配置不同的超时。支持可靠传输级会话的绑定为ReliableSession属性提供了用于配置空闲超时的InactivityTimeout属性。例如,下面示出了需要以编程方式配置的30秒以使TCP空闲超时结合的代码:

NetTcpBinding tcpSessionBinding = new NetTcpBinding(); 
tcpSessionBinding.ReliableSession.Enabled = true; 
tcpSessionBinding.ReliableSession.InactivityTimeout = TimeSpan.FromSeconds(30); 

下面是一个使用配置文件中的等效的配置设置:

<netTcpBinding> 
    <binding name="TCPSession"> 
     <reliableSession enabled="true" inactivityTimeout="00:00:30"/> 
    </binding> 
</netTcpBinding>