【问题标题】:WCF Session and connection to DBWCF 会话和与数据库的连接
【发布时间】:2013-01-29 22:55:41
【问题描述】:

我创建了与 SQL Server 建立连接并返回查询结果的 WCF 服务。

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

我想要的场景是:

  1. 在客户端输入SQL Server的用户名和密码,在服务器上建立连接(需要加密数据吗??)
  2. 保持会话 30 秒。

谢谢

【问题讨论】:

标签: c# wcf


【解决方案1】:

来自http://msdn.microsoft.com/en-us/magazine/cc163590.aspx,您可以使用Per-Session Services

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

会话默认为假。要支持会话,您需要在合约级别将 Session 设置为 true: [ServiceContract(Session = true)] 接口 IMyContract {...}

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

[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();

客户端和服务都可以通过在绑定中设置不同的值来配置不同的超时。支持可靠传输级会话的绑定为 ReliableSession 属性提供了用于配置空闲超时的 InactivityTimeout 属性。例如,下面显示了以编程方式为 TCP 绑定配置 30 秒的空闲超时所需的代码:

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>

【讨论】:

    【解决方案2】:

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

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

    如果您不使用 HTTPS,那么您是完全不安全的,您不妨一起删除密码要求,只允许任何人查询他们想要的任何数据。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      相关资源
      最近更新 更多