2012-11-25 108 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>