c# - WCF session 和到数据库的连接

标签 c# wcf

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

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

我想要的场景是:

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

谢谢

最佳答案

来自 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 默认为 false。要支持 session ,您需要在合约级别将 Session 设置为 true: [服务契约(Contract)( session =真)] 接口(interface) IMyContract {...}

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

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

每 session 服务和客户端服务代码

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

客户端和服务都可以通过在绑定(bind)中设置不同的值来配置不同的超时。支持可靠传输级 session 的绑定(bind)提供 ReliableSession 属性和用于配置空闲超时的 InactivityTimeout 属性。例如,下面显示了以编程方式为 TCP 绑定(bind)配置 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>

关于c# - WCF session 和到数据库的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13555327/

相关文章:

c# - 如何在一行中将字符串拆分和修剪成多个部分?

c# - WCF服务停止处理调用15秒钟

wcf - XML 注释未出现在 WCF 服务中

c# - Protobuf-net 不序列化基类成员

c# - 在 Windows Azure 中部署 WCF 应用程序

c# - ASP.NET MVC - 使用 MultiSelect 删除多行

c# - 以毫秒精度获取 DateTime.Now

c# - 如何在最后一个 '.' 值处拆分字符串

c# - 编写 PCI 兼容程序集需要什么?

wcf - 在 WCF 服务中重构上帝对象